#databases
1 messages ยท Page 97 of 1
how about two million entries and several thousand shards
if you're this worried about optimization, best thing to do is benchmark it
your simultaneous queries would be a problem
but that's going to be a problem regardless of database structure
honestly you're using a database for the exact use case it's designed for
I mean, the database is clustered
if you really have something like this, then you'd probably want to go to memcache
don't do that unless you're observing a reason to
if you don't have slow queries, you don't need to fix your slow queries
consider that the upgrade path
i just want a bunch of tips on how to optimize the querying so that thousands of servers can all access one database cluster with millions of entrys. That is my goal
shards* not servers
a single non-replicated database should be fine for what you said
you think so?
so you think bots such as Dyno use just one table for their server config
in terms of the query yes
if they're just getting one entry at a time
but in terms of number of simultaneous connections? you might have a latency issue
any ideas on how to minimize that?
but you should also be realistic about the number of connections and look at the issues as they happen
here's the thing
there are lots and lots of options
right now you are speculating on all the possibilities and trying to get a hole in one with your architecture and schema
this is a bad idea
you won't go from 0 to 10,000 simultaneous requests without hitting 250 first
it'll grow over time and you'll find out where the holes are
any tips on how to minimize latency?
use an in-memory datastore
so cache?
properly structured indexes
well I mean, cache in the shard
a cache will be trading one set of problems for another
so it only updates every so often
instead of always querying the database every time I need config
exactly, you're sort of implying that you can "max out your stats"
you can't, you can only move the points around
and one of those stats is "how long is it going to take me to build this thing" and "how much is it going to cost to maintain"
so what do you think my best bet in terms of data storage and latency?
sql with good indexes
define a "good index", currently they are just guild IDs, is that good?
I think your best bet is starting simple and finding out what the issue is when you look at the actual performance and then use that to perform benchmarks
if you're only querying using guildIds, then yes, that's a great index
so you say, go with one table, using the guild ID as index to start, then see what happens from there?
How long?
yeah, that'd be fine
how long do you think would make it not workable for you? bearing in mind parallel queries, and etc.
here's an example of my latency distribution for a 150MM row table
median response time is 40ms
yep, I get 30ms
bearing in mind, this is a 1cpu instance with 4GB RAM because it doesn't get much traffic
ok, thanks
also, I won't tell you to switch to postgresql, but it has a feature that lets you add indexes without locking table access
so if you need to add a new index while it's being used, you won't see much of a hit while doing it
how do i use select using psycopg2? i don't understand how fetchall works
nvm
well
should i commit when selecting things on a db? (psycopg2)?
oof
hello?
:(
no need to commit after selecting
in fact, if you're only using a transaction to select things, the typical pattern is to rollback to make sure you don't change anything that might've accidentally happened
as their name suggests
when you make changes in a transaction, these changes aren't applied permanently to the database until you commit
rollback to cancel the changes
@torn sphinx that's wrong syntax
UPDATE table SET value1 = 'one', value2 = 'two' WHERE something = something```
what is the postgres user password on ubuntu?
i install postgress, make role and create db, but never ask me for password
but i need enter password into my python connection
I tried like this: ALTER ROLE super WITH PASSWORD 'secret123'; to change password
but when i run python it gives error
that password auth failed
try logging in with psql first
then issue \password command
but also, if you don't have the right credentials, maybe google how to reset it, there is a way (I don't remember it)
If you finish a development SQL using mySQL, whats the steps to learning in python?
If you finish a development SQL using mySQL, whats the steps to learning in python?
@placid chasm start connecting mySQL to python
If you finish a development SQL using mySQL, whats the steps to learning in python?
@placid chasm And if you are a beginner then you should consider to first learn basics
If you've now learned SQL, and want to take the next step, one possible direction to go is to learn an ORM like SQLAlchemy
Guys, can someone recommend me a database I can use
I'm very sure I used the wrong terminology there
But basically what I'm asking is for some alternatives to SQL Server and MySQL
postgres
And can it be quickly started/shut down like MySQL?
I guess? you don't normally shut down SQL servers
For my usecase I need to be able to
That was the biggest advantage of MySQL, because I could instantly shut it down on click
why's that? maybe a different database is better in that case
I'm open to suggestions
well, SQL servers aren't supposed to be shut down, the fact that you can is probably somewhat incidental
The reason I am not using MySQL is because of the abysmal UI
eh?
And really it being very unresponsive at times
SQL servers don't have UI. you are using some kind of db tool (which might be the "official" mysql workbench), there are lots of different tools however
you don't have to use MySQL workbench to work with MySQL
It is
I'm not familiar with that
looking at the docs, doesn't seem like you can
DBeaver is general purpose database browser, it can work with several different kinds of database
DBeaver
the alternative I was going to mention was SQLite
SQLite is a file-based SQL database, which means there is no server
...Nope, I have used DBeaver before and I liked it, so I'll stick to it
SQLite is an alternative to MySQL or Postgres
the database exists as a file, rather than a server, which means there's no need to shut it down. when your application quits, everything's closed
useful for local usage, which I think is the same way you're using XAMPP right now
well, it's not a server at all, but in most use-cases, it works the same way like having an SQL server
you make the same queries. the SQL it uses is mostly the same as other databases
the only difference is it lives in a file on your disk, and there's no need to run a separate server. The client library in whatever language you're using will handle the file directly
Well then
Incidentally, DBeaver can also open SQLite databases
so DBeaver is also a useful tool for inspecting and manually managing your SQLite database
Wait I have a question now going into Django
Basically, I start my Django app with runserver right
But right now I need to open XAMPP as well to run mysql
if you use SQlite, I don't think you'd need XAMPP at all
mostly because XAMPP is a PHP/Perl stack with an Apache server. But if you're running Django, you're not using any of that, you're just using XAMPP for the database
its 90000000000% easier to just stick your django app in a docker container
and use the postgre image
so if you don't use MySQL and use SQLite or something, then you don't need XAMPP at all
Alright, I'll look into PostgreSQL
might be more of a webdev questions but I'll start here. I've hit a bit of a wall trying to figure this out and could use some advice. my question requires some context so here's the stackoverflow link. thanks! https://stackoverflow.com/questions/62820427/data-access-permissions-table
@round isle if your starting just starting with Django and you did not fiddle with the settings.py then you will be using the SQLite database
you won't need the XAMPP app anymore, then you can browser the database file with something like sqlitebrowser
using asyncpg executemany is really slow
async def on_ready(self):
await self.db.run()
await self.db.add_guilds(self.guilds)
await self.db.add_users([m for g in self.guilds for m in g.members])
# print(await self.db.get_all_users())
print(f'Logged in as {self.user}')
print('-----------------------')```
async def add_guilds(self, guilds: [discord.Guild]):
await self.conn.executemany("insert into guilds (id, msg_xp, level_msg) values ($1, $2, $3) on conflict do "
"nothing", [(guild.id, 0, False) for guild in guilds])
async def add_users(self, members: [discord.Member]):
await self.conn.executemany("insert into users (id, chat_level) values ($1, $2) on conflict do "
"nothing", [(member.id, 0) for member in members])```
the bot is only in 2 servers
and this takes like a full minute
is there something I'm doing wrong?
one of the servers has 1700 members the other has like 40
but I would think it wouldn't take so long
ok I used copy_records_to_table and it's much faster
but now I have to manually check that it's not already in the db
Yeah, I don't want to use SQLite, that's why I asked
Hey guys - I have one table in a database which I am going to use to serve to users of a web app. Essentially the table will be updated continously (~every 1-2 seconds) from a backend service and the web app will also call a flask API to read data from this table very frequently (~every 15-30 seconds) - Is there anything that I should be aware of when doing this or anything I should do to ensure stability? The table should be around 30k records with about 20-30 columns and each request from the web app will pull back a maximum of 50 results
The database is going to be posgresql
result = cursor.execute('SELECT user_id FROM economy WHERE user_id = ?', ctx.author.id).fetchone()```
This shows - ``parameters are of unsupported type``
How do I fix it?
I tried another method.
class database:
def field(self,command, *values):
cursor.execute(command, tuple(values))
fetch = cursor.fetchone()
if fetch is not None:
return fetch[0]
return```
```py
result = database.field('SELECT user_id FROM economy WHERE user_id = ?', ctx.author.id)```
This one shows error - ``operation parameter must be str``
Ok lemme try..
@brazen charm Hey it throws error - near "456055164886056961": syntax error
And I checked my db, user_id has INTEGER constraint!
Actually this works in my phone, but in pc its showing error..
The only way I'm able to solve this is by using f-string. But I don't want to use f-string.
is there a tool for converting sqlite3 syntax into postgresql?
I have schema (Postgres) like
CREATE TABLE config(
disabled_channel_ids bigint[] DEFAULT array[]::bigint[],
current_raffles jsonb
);```
and queries like
```sql
UPDATE config SET disabled_channel_ids = array_append(disabled_channel_ids, 1213::bigint);
SELECT * FROM config;
but it's not doing anything. no errors but doesn't work either. can someone tell me what's the problem here?
is there a way I can transfer an sqlite db to mysql
(something with server support)
@short vortex pretty sure any sqlite queries are valid Postgre queries
that depends on the drive
psycopg2 is %s yes but postgre's system is $1 univerally
but psycopg2 like to be dumb
@torn sphinx do you not COMMIT;
I need to commit after that?
i mean how else do you expect it to save?
Hello
So guys accessing a pickle database vs pandas dataframe on ram. Pickle would be as fast as reading data in of dataframe?
Of course I'll need to import the data in pickle as a dataframe
idk i never had to commit when using insert queries so i wasn't sure
you have to commit after insert queries unless you specify auto commit in your config
you probably dont need to commit if you didnt need with insert
Heres a simple question, but I was having some trouble in wording it for a google search ๐
Lets say I have 2 data tables (A and B) and a table that links them both together (X). If I had classes application-side that represents this data, would it be best to run one JOIN query that fetches all the data or run 3, one to select a row from X, then 2 more to query the data tables?
Not really looking in terms of speed, just sort of a standard
this is a many-to-many relationship, and you should JOIN
table X is called a junction table
(or join table, or associative table)
I hope these words are useful for your search
Thanks for the specific terms, I did know this just forgot
๐
So in that diagram, say actor had a lot of columns and so did film
You should still do a join, and receive all info about the actor and film in one row
I think so yes
hmm ok
query = "UPDATE bump SET bumps=bumps+1, last_bump= the current timestamp WHERE memberID=" + author_id
Quick question, could someone please tell me how I'd add a timestamp to my update query so I can put it into my database? It would go after last_bump=
don't build sql queries with string concatenation
what kind of database are you using?
with sqlite you can do ```py
cursor.execute("update bump set bumps=bumps+1, last_bump=datetime('now') where memberid = ?", [author_id])
you could also generate the timestamp in python instead, if you're going to need to use it after the query
using time.strftime or stuff in the datetime module, and then ```py
cursor.execute("update bump set bumps = bumps+1, last_bump = ? where memberid = ?", [timestamp, author_id])
I am using mySQL
ok then it's basically the same but %s instead of ? (despite the appearance of %s this isn't really the same thing as string formatting, as long as you do not use "query" % [arguments])
er
wait what is the type of the last_bump column
sqlite doesn't have a real datetime so i was assuming string but in mysql what are you using
and which mysql library are you using
you can probably use current_timestamp() [instead of datetime('now')] if you don't need to generate the timestamp in python
it is a timestamp
ok i think you can pass a string in YYYY-MM-DD HH:MM:SS format into that, and that is what current_timestamp() returns
what is the type of memberID and author_id ?
authord_id is a string
even though its just got numbers in
memberID is an int so there is probably an issue there
but if I set author_id to an int would it not cause issues with my statement query since that is a string?
like i said
don't do "update..."+author_id
use the execute with list of parameters syntax
you haven't shown me the line where you call execute so i can't rewrite the whole thing for you
query = "UPDATE bump SET bumps=bumps+1, last_bump= %s WHERE memberID=" + author_id
values = (datetime.datetime.utcnow(),)
cursor.execute(query, values)
db.commit()
but for an example py cursor.execute("update bump set bumps = bumps+1, last_bump = current_timestamp() where memberid = %s", [author_id])
or you could do that
er i don't know if datetime works directly
but then
neither do I
query = "UPDATE bump SET bumps=bumps+1, last_bump=%s WHERE memberID=%s"
values = (datetime.datetime.utcnow(),author_id)
hmm ok, thanks. I have a feeling datetime doesn't work though so I will need to find an alternative.
like i said, you could use current_timestamp() in sql, or once you have utcnow() call .strftime() on it
ah ok
Does anyone have any experience connected to a .sdf DB with Python. I just have the file, so something like pyodbc would be necessary? I am really not sure where to start
This is database class
And this is a command
It always throws this error - operation parameter must be str
How can I fix it??
Well that's right @south meadow it's correct error
Emoji is an str
U r giving emoji as int
And u also haven't made connection
So how it will work
Lol haven't scrolled up
And what emoji has to do with database?
xD
Is this error coming cuz of database or something because of emoji? @steady epoch
Check the class bruh, it has fetchone() func
Lol
๐
Check correctly
It must have shown multiple lines
@south meadow is your user id is defined as int or str when u created db?
Check that
@steady epoch user_id is INT in db
And also it doesn't show any error without try/except
Can I check how r u creating your db?
umm ok!
Check whether it works or not
@steady epoch Bruh! Neither it's showing any error nor it's replying....tf!
The file in which u r using this command have u imported sqlite3
Everything works fine if I run it in my phone.
The file in which u r using this command have u imported sqlite3
@steady epoch yep
@steady epoch No I hosted it on heroku and tried there but then also same error comes...
@south meadow heroku don't support sqlite3
It only support postgres sql
That is also limited
Ok
And I managed to find the full error..
Ignoring exception in command balance:
Traceback (most recent call last):
File "C:\Users\harsi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "d:/Unusual_Coder/bot.py", line 80, in balance
raise e
File "d:/Unusual_Coder/bot.py", line 66, in balance
result = database.field('SELECT user_id FROM economy WHERE user_id = ?', ctx.author.id)
File "d:/Unusual_Coder/bot.py", line 33, in field
cursor.execute(command, tuple(values))
ValueError: operation parameter must be str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\harsi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\harsi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\harsi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: operation parameter must be str```
I tried it in another bot
and full error came huh
@steady epoch
cur.execute(f"SELECT clan_tag from clan WHERE discord_id = {member.id}")
@south meadow I do like this
I know I can do that..
That works also..
But I don't want to use f-string...
@steady epoch
Well then I don't know
I do that way only
I don't try different stuff unless I feel to change @south meadow
@steady epoch You should not use f-stings because it makes your code and db vulnerable and might get an SQL Injection attack!
๐ค
Hi all, I'm learning Python & following this tutorial (https://realpython.com/flask-by-example-implementing-a-redis-task-queue/). It's really good but I'm having this odd error where I can't add items to postgres DB after I link a Redis worker to Python. The thing I don't get is that postman gives me a 200 & so does the terminal. The error occurs in line 63 of app.py in this repo (https://github.com/MartinScriblerus/LanguageProcessing)... here is the error-causing code:
try:
result = Result(
url=url,
result_all=raw_word_count,
result_no_stop_words=no_stop_words_count
)
db.session.add(result)
db.session.commit()
except:
errors.append("Unable to add item to database.")
return render_template('index.html', errors=errors, results=results)
anyone know any good services to host databases. i kinda dont want to use aws
anyone know any good services to host databases. i kinda dont want to use aws
@torn sphinx if you are looking for free ones, then go for glitch
def databaseWrite(guild, data_write, data_in):
conn = sqlite3.connect('./Servers/DB/settings.sqlite')
cursor = conn.cursor()
if cursor.execute(f"SELECT COUNT(*) FROM messages WHERE guild_id={str(guild)} AND {data_in}={str(data_write)}").fetchone()[0] != None:
try:
print("Print database 0/1")
cursor.execute(
f"""INSERT INTO messages({str(data_in)}, guild_id) VALUES({str(data_write)}, {str(guild)})""")
conn.commit()
print("Print database 1/1")
except Exception as e:
print(e)
return
else:
print("Reload database 0/1")
cursor.execute(
f"UPDATE messages SET {data_in}={str(data_write)} WHERE guild_id={str(guild)}")
conn.commit()
print("Reload database 1/1")
I do that but I always have the mm bp each time it prints and it does not relaod
when I launch the commabde it rewrites the value below
Ho no
It's good
hi! i really need someone who's good at pymongo and know discord.py too
i'd like to confide if my code will work
because i don't wanna mess things up at my collection
Whats the difference in both
The second works fine while first js throwing errors
Ignore .ojsk py its command of my bot
Hey guys, can this query be translated to Sqlalchemy? I am unable to find any proper examples.
UPDATE users
SET amount =
CASE
WHEN exp BETWEEN 10 AND 199
THEN 10
WHEN exp BETWEEN 200 AND 499
THEN 20
WHEN exp BETWEEN 500 AND 999
THEN 40
WHEN exp BETWEEN 1000 AND 1999
THEN 100
ELSE amount
END
why do it in SqlAlchemy when you've made the query??
I am refactoring my code and wanted to move all manual queries to sqlalchemy.
nvm, figured it out xd
Hi all, been directed here from the help channels.
I am a bit of a novice to Python but am learning by doing.
Currently working on trade data analysis and so, I've requested data from an exchange's API for a given interval of 1hour but this provides "tick by tick" data for that whole hour, however, the OHLC data I am interested in happens in the last tick of that hour. Does anyone know of a reasonably straightforward method to access the last tick slice in each hour so I could pull the OHLC (and V if wanted) so I can populate a new CSV file?
how to use redis for cache in Python i m using psql at the time
@glad rune Can you specify what code you think is the problem?
for sure... (it is just a novice guess... the tutorial is really good by the way...)
Hey @glad rune!
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:
app = Flask(name)
app.config.from_object(os.environ.get('APP_SETTINGS'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
q = Queue(connection=conn)
#I THINK THIS IS THROWING THE ERROR
from models import *
#Can't find a results table in here
def count_and_save_words(url):
that is a condensed version of app.py
from app import db
from sqlalchemy.dialects.postgresql import JSON
class Result(db.Model):
tablename = 'results'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String())
result_all = db.Column(JSON)
result_no_stop_words = db.Column(JSON)
def __init__(self, url, result_all, result_no_stop_words):
self.url = url
self.result_all = result_all
self.result_no_stop_words = result_no_stop_words
def __repr__(self):
return '<id {}>'.format(self.id)
this is all of models.py
I'm getting a SQLAlchemy exc.operational error that there is no such table called 'results' in db
or I get an Assertion or an Attribute error when I move things around.
Assuming your model still just contains Result, have you tried from models import Result instead of *?
I'll try that
hmm... sqlalchemy.exc.OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: results
[SQL: SELECT results.id AS results_id, results.url AS results_url, results.result_all AS results_result_all, results.result_no_stop_words AS results_result_no_stop_words
FROM results
Have you run your database migrations?
ah... let me try that...
I had run them initially & it worked but hadn't run again since updatiing w/ redis queue
Did that fix it for you?
can anyone help me with aiosqlite3
so i am changing my sqlite3 codes to aiosqlite3 and thx for @zinc harness i messed up
and i think it can be fixed
but idk how
it has few problems
most of them is about aiosqlite3
Hello! So im a little suck trying to host a database on heroku
I was wondering if anyone knew some stuff about how we can set it up?
If so please tag me <3
Hi @torn sphinx ... parts 1 and 2 of this tutorial discuss postgres on heroku https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
I got it to work by following parts 1 & 2 exactly, with the exception of the os.environ variables, which seemed to work with os.environ.get() instead of os.environ[]... otherwise, it worked great for heroku.
Can anybody explain? It's mongoDB. I'm trying to create an restricted user, but I don't see any database other than authentication one, even though I have dbOwner on another one.
the cursor.
@torn sphinx
yes - if you're able to use the Connection at all, that's an extension on top of what the Python DB-API requires, and writing your code to be as compatible with the DB-API as possible will make it more portable to other databases down the line should you ever choose to move it
The DB-API only has execute() on Cursor's, not on Connection's.
@torn sphinx no, executemany takes a single statement, and a list of parameters, and runs the same statement repeatedly with different params. And it's unspecified how to get results out if the statement produces result sets, so it's really only useful for DML - insert/update/delete, etc
Hey uh, How would I go about connecting to an sqlite3 db file from a different directory?
I know how to connect to one in the same but different directories are harder
?
you just pass the full path to it (either absolute or relative)
Windows or Unix, @torn sphinx ?
so you can do something like sqlite.connect('/path/to/my.db')
Let me try that
Lets say the directory is this:
currentdirectory/cogs/my.db
do I just do cogs/my.db
Aye
let me try a sec good gent
It worked
Thanks gent.
Damn, python server so friendly isn't it?
result = [code + "โ โ" + name for code, name in zip(df["DX_CODE"], df["DX_NM"])]
I'm trying to join items from two columns together, and I have the above line
However, it breaks whenever code is None
How can I change it so that it can handle Nones?
result = [str(code) + "โ โ" + str(name) for code, name in zip(df["DX_CODE"], df["DX_NM"])]```
seems to work, but is that bad practice?
python bois raise up! I need some help
How would I go about adding money to a balance?
Is it a bit like py SQL2.execute(f'update profiles set balance = "+2500"')
more like set balance = balance + 2500
I have a question regarding SQLAlchemy, is someone familiar with how relationships are handled in it?
So in SQLAlchemy, I've been playing around with it a bit and have a relationship defined with the relationship("RedditUser") method. When I use session.query(DiscordUser).join(RedditUser) I only get users that have one or more of those relationships. But if I do it without the join and just manually access the relationship via DiscordUser.reddit_accounts I see any if they're present, so does this mean I should use join() as a filter so to speak only if I need the users with connected accounts?
sqlite 3
How I can search some user at 2 phonetics?
I need help with the Rollback function in sqlite 3
As an example, even if i raise an error in the middle of the execution the first Table drops anyway o.o
Does anybody know why.
if ask == 1:
try:
cur.execute("DROP TABLE Projects")
raise sqlite3.OperationalError
cur.execute("DROP TABLE Temp")
print("Droping Database Tables")
except sqlite3.OperationalError:
conn.rollback()
messagebox.showinfo(title="Datenbank Reset", message="Anscheinend sind keine Daten vorhanden.")
else:
conn.commit()
last time i checked SQLite had no rollback system
Ignoring exception in command flarieinfo:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 503, in flarieinfo
ctries = gettries(message.author.id)
File "/home/pi/hangit/database.py", line 83, in gettries
c.execute(sql, (MemberID,))
sqlite3.OperationalError: no such column: Tries
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: Tries
Why does this come up even though I have a column called Tries?
Code
def gettries(MemberID):
conn = sqlite3.connect('Flarie.db')
c = conn.cursor()
tblFlaire = "Flariepoints"
sql = f'SELECT Tries FROM {tblFlaire} WHERE MemberID = ?'
c.execute(sql, (MemberID,))
Tries = c.fetchone()
conn.commit()
conn.close()
return Tries
(when I call this function)
Can someone help me send information to a db ?
i am very stuck
using sqlite3 ??? or should i use mongodb
Not yet @tough needle literally only just started
basically i just want to store discord bot data in a db but need help setting it up and then using it for different stuff
okay you able to help?
Yes, so first of you should install sqlitebrowser
Then you need to create a database, easiest way to do this is through code
i mean isnt it easier to make it in the browser?
It's safer to do through code
okay then
Here's one of my examples:
conn = sqlite3.connect('Flarie.db')
c = conn.cursor()
tblFlaire = "Flariepoints"
sql_create_table = """CREATE TABLE IF NOT EXISTS Flariepoints
(Name text NOT NULL,
Points integer,
MemberID integer PRIMARY KEY)
"""
c.execute(sql_create_table)
conn.commit()
can i use it?
thats similar to what i had before then i got told to add in async
So Flarie.db is YourName.db
kk
Flariepoints is YourTableName
Name is column1
Points is column 2
MemberID is column 3
@tough needle idk if you know this question but where abouts do i put it in my dpy script? In main one?
Oh I have no idea
okay one moment
okay found it
so i have taken out column 3 as i only need guild id and channel id i think
@tough needle Done that part whats next?
Now you have a databse and if you want to edit it you need to define a function for it
for example:
def editcolumn1(Column1name)
conn = sqlite3.connect('dbname.db')
c = conn.cursor()
tblName = "tblname"
sql = f'INSERT INTO {tblName} VALUES ({Column1name})'
c.execute(sql)
conn.commit()
conn.close()
ok
im getting an error where the bracket on the end of (Column1name) it says invalid syntax
add :
okay now conn is erroring with the same error directly below that line
i just realised i did the wrong columns so now there is user, guild and reason does this affect what i already have?
what next tho @tough needle
smol help?
???
how can we sort data from an api output
idk
:/
Hello, I'm trying to use Postgre and Redis with Python, but my program keeps reverting to SQLite (which is not set up) when I hit the route of my Redis worker. Any idea what might be causing this?
how are you connecting to the db in your redis worker?
I am using psycopg2-binary and sqlalchemy and running a worker.py file that listens for input on Flask frontend & sends jobs to redis through these lines:
from sqlalchemy.dialects.postgresql import JSON
from psycopg2.extensions import register_adapter
register_adapter(dict, JSON)
def count_and_save_words(url):
errors = []
try:
r = requests.get(url)
except:
errors.append(
"Unable to get URL. Please make sure it's valid and try again."
)
return {"error": errors}
# text processing
raw = BeautifulSoup(r.text).get_text()
nltk.data.path.append('./nltk_data/') # set the path
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
# remove punctuation, count raw words
nonPunct = re.compile('.*[A-Za-z].*')
raw_words = [w for w in text if nonPunct.match(w)]
raw_word_count = Counter(raw_words)
print(raw_words)
# stop words
no_stop_words = [w for w in raw_words if w.lower() not in stops]
no_stop_words_count = Counter(no_stop_words)
print("HERE IS DB JUST PRIOR TO INIT SESSION", db)
# save the results
try:
result = Result(
url=url,
result_all=raw_word_count,
result_no_stop_words=no_stop_words_count
)
print(result)
print("HERE IS DB JUST PRIOR TO INIT SESSION", db)
db.session.add(result)
db.session.commit()
return result.id
except:
errors.append("Unable to add item to database.")
return {"error": errors}
R=0
app = Flask(name)
app.config.from_object(os.environ.get('APP_SETTINGS'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
q = Queue(connection=conn)
print("HERE IS DB JUST PRIOR TO INIT SESSION", db)
class Result(db.Model):
tablename = 'results'
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String())
result_all = db.Column(JSON)
result_no_stop_words = db.Column(JSON)
def __init__(self, url, result_all, result_no_stop_words):
self.url = url
self.result_all = result_all
self.result_no_stop_words = result_no_stop_words
def __repr__(self):
return '<id {}>'.format(self.id)
@app.route('/', methods=['GET', 'POST'])
def index():
results = {}
if request.method == "POST":
# this import solves a rq bug which currently exists
from app import count_and_save_words
# get url that the person has entered
url = request.form['url']
if not url[:8].startswith(('https://', 'http://')):
url = 'https://' + url
job = q.enqueue_call(
func=count_and_save_words, args=(url,), result_ttl=5000
)
print(job.get_id())
return render_template('index.html', results=results)
This function makes the postgresql set up disappear & replaces with SQLite.... I believe it's due to this message: 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
can you toss that into here so it's easier to read https://hastebin.com/ ?
for sure! thanks!
here is a link: https://hastebin.com/raw/efujawiyab
so I read this SO & moved models.py class into this app.py, but it still isn't working right: https://stackoverflow.com/questions/57720565/flask-sqlalchemy-neither-sqlalchemy-database-uri-nor-sqlalchemy-binds-is-set-d
app.config.from_object(os.environ.get('APP_SETTINGS'))
what is APP_SETTINGS in your env?
strange ... -bash: syntax error near unexpected token `os.environ.get'
does this mean I missed an important step?
that's python code, not shell code
looks like your config is missing SQLALCHEMY_DATABASE_URI
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
that's where you specify how to connect to your db
In my initial setup, the terminal says I have a postre database
it just changess once I hit that URL route.
can you show me how it says that?
sure
here's a stacktrace from app.py that shows it going to postgre to sqlite (but the actual sqlite shows up in worker.py, which I'll send next) : https://hastebin.com/raw/doyekaseso
that looks like the stacktrace got cut off at the bottom and it missing the actual exception
ok, here's the worker.py w a bunch of text data from url: https://hastebin.com/raw/geziruzoko
sorry! this is the last part of app.py terminal w/ exception regarding JSON "get quoted": File "/Users/matthewreilly/Desktop/LanguageProcessing/env/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 593, in do_execute
cursor.execute(statement, parameters)
AttributeError: 'JSON' object has no attribute 'getquoted'
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [13/Jul/2020 02:55:04] "GET /results/d8ac945c-1fc8-40de-94c6-71c05ef8def7?debugger=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
- Detected change in '/Users/matthewreilly/Desktop/LanguageProcessing/app.py', reloading
- Restarting with stat
Redis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
HERE IS DB JUST PRIOR TO INIT SESSION <SQLAlchemy engine=postgresql:///wordcount_dev>
Python-dotenv could not parse statement starting at line 1
python 3.6?
yep
well good luck
is that bad news?
i have no knowledge on this topic yet
is that bad news?
probably
the website actually says what went went wrong
where should I look?
app.py 32? from 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
HERE IS DB JUST PRIOR TO INIT SESSION <SQLAlchemy engine=sqlite:///:memory:>??
The code that caused this warning is on line 32 of the file /Users/matthewreilly/Desktop/LanguageProcessing/app.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor.
sorry if that wasn't helpful
so would that look like raw = BeautifulSoup(r.text, 'features="html.parser"').get_text()?
no need for the single quotes
and that's not causing the issue
it's the other warning
/Users/matthewreilly/Desktop/LanguageProcessing/env/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
cool... just checking raw = BeautifulSoup(r.text, features="html.parser").get_text()
yes ๐
try:
SQLALCHEMY_DATABASE_URI='postgresql:///wordcount_dev' python3 worker.py
when you run it in your terminal
ahhhh
got it
ok so I got this error: AttributeError
AttributeError: 'JSON' object has no attribute 'getquoted'
which is in above stack trace. I ran this in virtual env with worker py & also started app.py in virtual env (w another terminal that has redis-server started
which line causes that?
here is the full; trace: https://hastebin.com/raw/vudoxayugo
File "/Users/matthewreilly/Desktop/LanguageProcessing/app.py", line 116, in get_results
in context:
print("THIS IS CONNECTION", conn)
if job.is_finished:
print(R)
result = Result.query.filter_by(id=job.result).first()
results = sorted(
result.result_no_stop_words.items(),
key=operator.itemgetter(1),
reverse=True
)[:10]
print(jsonify(results))
return jsonify(results)
I have these JSON things imported as well (not sure if that's c ausing.) .........
from stop_words import stops
from collections import Counter
from bs4 import BeautifulSoup
from sqlalchemy.dialects.postgresql import JSON
from psycopg2.extensions import register_adapter
register_adapter(dict, JSON)
did this to stop a "dict" error from psycopg2-binary
does anything in that above code (or the imports) seem like it would set off the JSON object getquoted error?
okay i have just started doing python again after being forced to in school and hating it, this time its enjoyable but holy shit u guys make it so confusing hahaha
if cursor.execute('SELECT COUNT(*) as count FROM users WHERE party = ?', (pname,)).fetchone() <= 5:
How fix?
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\L7ky Party\party.py", line 73, in __invite
if cursor.execute('SELECT COUNT(*) as count FROM users WHERE party = ?', (pname,)).fetchone() <= 5:
TypeError: '<=' not supported between instances of 'tuple' and 'int'```
fetchone gives you a record, not a single value
Hi all... been struggling with this SQLAlchemy bind error above (for the past 2 days!!) & I finally got it working thanks to lots of good advice from this forum & especially from @runic pilot. So... if anyone runs into SQLAlchemy binds not being set, the third line below is what fixed it for me:
app = Flask(name)
app.config.from_object(os.environ.get('APP_SETTINGS'))
app.config['SQLALCHEMY_DATABASE_URI'] =
os.environ.get('DATABASE_URL')
db = SQLAlchemy(app)
ok so do you want it all in the same table then?
i dont know what is more practical
hmm
and if you want bans for instance select * from punishments where type= 'B' and user_id=1231233213123123
cuz bans, warns, and kicks can all have an optional reason
I see SQLite uses C, will i have to use C?
nope
okie
thats the library you're gonna wanna use to interact with the db
Hey guys hopefully just a quickie cant get this to work - query = "SELECT * FROM servers.servers WHERE last_updated > NOW() - INTERVAL 1 MINUTE" return await database.fetch_all(query=query)
Im trying to get records that are 1 minute old based on last_updated i am using postgres as my database and sqlalchemy as interface with encode.io/database
o
havent used the db or interface personally turbo, so im at a loss 
aoa
No problem im learning it my self, this is my first time doing PY thon and Postgres i do use ASP.NET & MYSQL on a daily tho
uhm what do i do
ok so
still stuck on what to do here
what data do you wanna store
Warnings at the moment
amount of warns would be in code
Yeah thats understandable
you'll want a warn id to clear them later if needed
@clear reef before you start creating a rational databse u should probably look into 3nf and plan it out as it can get messy real fast. think of what data types they need to be and how many tables you need then the create table part is easy.
i mean warnings are pretty straightfoward
Yeah i have no idea waht im doing
this is how my warns table is set up
an id that goes 1, 2, 3, 4, ... as more are added to the table
I see
staff is the ID of the staff member, user is the ID of the warned user, etc
an id that goes 1, 2, 3, 4, ... as more are added to the table
@torn sphinx
well you dont want certain things to be able to be Null
thats what the NN (NOT NULL) checkbox is for
the ones that have to have a value
????
that works
except
i use cleared to allow warnings to be cleared
so it has a default value of 0
I understood so
(1 if cleared)
mhm
so you can set defaults there too
so not null
i iddnt make it NN cuz i had a default but yea you can
aoaoa so no checked boxes?
https://aiosqlite.omnilib.dev/en/latest/?badge=latest
https://www.tutorialspoint.com/sqlite/sqlite_syntax.htm
btw
SQLite - Syntax - SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax.
and no i didnt have any
and the reason didnt need any either
nope, cuz it's optional in my case
yup
then click "write changes"
then file > close db
file > open db read-only
so db browser doesnt lock the db
the rest of the warnings is python now
i just created a whole database?
you just created a table
https://aiosqlite.omnilib.dev/en/latest/?badge=latest
https://www.tutorialspoint.com/sqlite/sqlite_syntax.htm
keep these handy
SQLite - Syntax - SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax.
then install aiosqlite with pip
however you would in your ide/editor
file > open db read-only
and if you do this you can see the rows your bot adds to the table
python -m pip...
its alright
yup
aiosqlite
yup
also
that changes the working directory (place where files are looked for) the the folder bot.py is in
ooh
but
i have seperate folders
i only need to import in my moderation one
where the warn command is located
then yup just there
welp so do you have a warn command yet
i do
alr
probably hella messy
async with aiosqlite.connect(...) as db:
await db.execute("INSERT INTO some_table ...")
await db.commit()
async with db.execute("SELECT * FROM some_table") as cursor:
async for row in cursor:
...
this is the basic pattern
well you want it in your warn command
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.has_permissions(kick_members=True)
async def warn(ctx, member : discord.Member, *, reason=None):
if member.top_role >= ctx.author.top_role:
ctx.send(f"You cant warn someone higher ranked than you, {ctx.author.display_name}")
return
await ctx.message.delete(delay=None)
if member == ctx.author:
await ctx.send(f"You cant warn yourself, {ctx.author.display_name}...")
return
embed = discord.Embed(
colour=discord.Colour.red(),
title=f"**Reason:** `{reason}`"
)
embed.set_author(name=f"{member.display_name} has been warned by {ctx.author.display_name}", icon_url=f"{member.avatar_url_as()}")
await ctx.send(embed=embed)
embed = discord.Embed(
colour=discord.Colour.red(),
title=f"**Reason:** `{reason}`"
)
embed.set_author(name=f"You've been warned by {ctx.author.display_name}\nIn {ctx.guild.name}", icon_url=f"{member.avatar_url_as()}")
await member.send(embed=embed)
and you're gonna want something like
async with aiosqlite.connect("asdsadas.db") as db:
await db.execute("INSERT INTO warns(user, staff, reason, timestamp) values (?,?,?,?)", (warned_user_id, staff_id, reason, datetime.datetime.utcnow().timestamp()))
i do that here https://github.com/united-minecrafters/kaede/blob/master/cogs/administration/punishments.py#L34
basically how INSERT works
INSERT INTO table_name(column1, column2) values (value1, value2)

hm ok so
make a new db in dbbrowser (if you middle click on the taskbar program, it''l open another copy of the program)
and do file > new in-memory db
mhm
alr so
go over to the execute sql tab
type thgat
ctrl + enter
*that
you'll see the new row
ok welp
where
apparently you cant name a column default
oh here
db structure tab, right click table, modify
xd
you can see how the default was overridden
number incremented itself
so small 
i know 
o
make a few duplicate defs or texts
wah
...?
use the insert into statement to add a few more records
so i can show you select, update, and delete :p
u
?
howsies
if you double click a cell, you can edit it in the right side
you never set a defaukt, mine was 1
nope
frick
you selected all the rows where def was 4
this is how you'd get warns for a user, for instance
not the 5's
yup
this is how you'd get warns for a user, for instance
@torn sphinx it checks for their name and then checks thei info such as amount
yes?
so do you understand how insert and select work?
i guess
you'd count the rows in the code
so if i was like
p.warnings @clear reef
it would use my id
267689225112125441
to check
and then fetch info
yup
so 2 more important statements
mhm
im guessing you cna use that to clear warns
yeah it gone
ok so
last one
update
this is how you probably want to clear warns
you set cleared to 1
im getting the hang of it
update
delete
insert
select
mhmm
those are the most frequent ones you'll use
i see
add a few more records , with different def values
run this
and it's DESC counterpart
yup ;3
this ranked the numbers?
yup
notice that the resulting table is only number and text
also, if you want to, say, get the 3 highest defs
i cant do text
hm?
odd mine doesnt
and it does nothing
oh right lol
:p
huh
ok so
you have your first 3
(your first page)
note that number is a primary key
and has to be unique
so if i
5 was the last number
so i can just
theres the next page
8 is the last number
last page
i see
anywho
so you think ya get all that enough to put it into practice?
and you're gonna want something like
async with aiosqlite.connect("asdsadas.db") as db: await db.execute("INSERT INTO warns(user, staff, reason, timestamp) values (?,?,?,?)", (warned_user_id, staff_id, reason, datetime.datetime.utcnow().timestamp()))
@torn sphinx something like this
hm
the ? tells sqlite to use one of the passed values, and gets escaped to prevent sql injection
mhm
so that'd be the basic add-a-warn code
where in my warn code would i be putting this
wherever you feel is best
im talking about indention as well
change warned_user_id, staff_id, reason, etc to whateveryou have to
indent the async the same level as the rest of the code inside the functiopn
indent await 1 tab after async
well staff_id is probably ctx.author.id
reason is reason
and it looks like warned_user_id is member.id
oh
you need an await db.commit() to record changes
inside the async
after the execute
yes?
ill open
make sure it's read-only
or else the program locks the database and you cant edit it in your bot
so its read only rn
and now i just execute the command
?
and check the "browse data"
hm
uhm
excuse me what
why vsc
and you're sure you're acessing the right db?
what else is there to visit
are you accessing "Data.db" in the code?
uhhh
cuz remember, warns is a table in that db
where
in your connect
oop
poor saber ):
you're looking at the wrong table :p
oop-
:D
GAMER MOMENT
except
.
shut down your bot and make cleared have a default :p
you'll have to reopen the db in db browser
how do i make it have a default again


