How to check if TABLE creation was successful in Sqlite (python)? - python

An EXISTS is no good since I need to know whether this particular function was the reason behind a successful Table creation or not, not whether the table exists (since it might already exist from somewhere else). If the function successfully created the table, something will happen. If it didn't (the table already exists, doesn't exist but table creation still failed) then nothing will happen.
It's easy to check if SELECT successfully selected something (eg: c.fetchone()[0] > 0), it's easy to check if UPDATE succesfully updated something (eg: c.rowcount>=1), how to easily check if CREATE TABLE successfully created a table?

Related

How I can get updated, created or failed data after insert into table?

I have a lot of objects that need to be inserted into the table. After insertion, there may be three options: created, updated and failed. It looks like upsert but I need a detailed result.
I tried to use on_conflict_do_update but then I won’t find out which ones were updated, created and failed.
I really do not want to use iteration and handle each item in exception block, maybe you will have some options?
What do you want to do with the information? One way to do this is by using Postgres triggers that execute specific actions when a row is inserted or update. Define a trigger that executes a function before insert or update on your table. Handle what you want to do with the created/updated data in the trigger function.
CREATE FUNCTION handle_modify() RETURNS trigger AS $modify$
BEGIN
IF TG_OP='INSERT' THEN
--do something with created data NEW.data
END IF;
IF TG_OP='UPDATE' THEN
--do something with updated data NEW.data or OLD.data
END IF;
END
$modify$ LANGUAGE plpgsql;
CREATE TRIGGER modify AFTER INSERT OR UPDATE ON your_table
FOR EACH ROW EXECUTE PROCEDURE modify();

How could I check - does my SQLite3 database is empty?

I am using Python 2.7 and SQLite3.
When I starting work with DB I want to check - does my database is empty or on not. I mean does it already have any tables or not.
My idea is to use the simple SELECT from any table. And wrap this select in try:exception block. So if exception was raised then my DB is empty.
Maybe someone know the better way for checking?
SELECT name FROM sqlite_master
while connected to your database will give you all the tables names. you can then do a fetchall and check the size, or even contents of the list. not try/catch necessary (the list will be empty if the database doesn't contain any tables)

Did CREATE TABLE IF NOT EXISTS create the table?

import sqlite3
connection = sqlite3.connect("...")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS ...")
How can I find out, after executing the CREATE TABLE IF NOT EXISTS, whether the table was created or already in place?
The only way to check is by removing the IF NOT EXISTS part of the query and checking for a sqlite3.OperationalError with a message of the form "table $tablename already exists". I wouldn't trust the error message to be stable, but Python apparently does not supply an error code along with the exception.
The safest thing to do would be to begin a transaction and query the sqlite_master table beforehand, create the table if there were no results, then commit the transaction.
Note that none of these solutions will work correctly if the table you are attempting to create has a different schema than the one that exists in the database; database migrations are more complicated and usually require case-by-case handling.
EDIT: Updated answer
It sounds like you don't know beforehand what tables might exist, what those tables have in them (if anything), or have a way to check beforehand if tables exist.
To check if a table was created after using the IF NOT EXISTS clause on a CREATE TABLE command, you could try one of these:
Make the "new" table have at least one column name that is guaranteed to be different from the old table. After the CREATE TABLE command, you select the column guaranteed to be new.
CREATE TABLE newTable IF NOT EXISTS (column1 INTEGER, somethingUnique INTEGER)
SELECT somethingUnique FROM newTable
If you don't get back an error from selecting somethingUnique, then you know that you have created a new table, else the table already existed. If you end up creating a new table and do not want that somethingUnique column anymore, then you can just delete that column.
Even if you don't want to make a somethingUnique column, there is the possibility that if the old table existed, it would have at least one row in it already. All you have to do is select anything from the table. If nothing returned, then you may or may not be dealing with your new table (so go back to suggestion 1). If something does get returned, then you know that you are dealing with an old table.
Old answer
One way to see if the table was created (or exists) is to go into a terminal, navigate to the directory where your database is, and then use sqlite commands.
$ sqlite3
sqlite> .open yourDatabase.db
sqlite> SELECT * FROM theTableYouWantedToCreate;
If the table does not exist, you would get back the following error:
Error: no such table: theTableYouWantedToCreate
If the table did exist, obviously it would return everything that is in the table. If nothing is in the table (since you just created it), sqlite will give you back another prompt, indicating that the table does indeed exist.

Check for duplicates in sqlite3 database and return error if any

I have a sqlite3 database file with multiple tables, each one with different values, what i want to do now is to check if a value already exists in any table when inserting it to the table and if it already exists returns an error or something.
This is because I'm doing a program t help nurses have a database with their patient and check if a patient has already been inserted into the database, I dont post any code because i'm gathering all the information needed before programming anything to avoid spaghetti code
Try adding a constraint to each or just one of your columns so I doesn't allow duplicates to be added
Like this:
CONSTRAINT <Constraint Name> UNIQUE (<column1>,<column2>)
Then in your code you could catch the SQL exception and return a custom message

Python + Cassandra 1.2 automatic table creation

Intro
I'm writing an application in Python using a Cassandra 1.2 cluster (7 nodes, replication factor 3) and I'm accessing Cassandra from Python using the cql library (CQL 3.0).
The problem
The application is built in a way that when trying to run a cql statement against an unconfigured column family, it automatically creates the table and retries the cql statement. For example, if I try to run this:
SELECT * FROM table1
And table1 doesn't exists, then the application will run the corresponding CREATE TABLE for table1 and will retry the previous select. The problem is that, after the creation of the table the SELECT (the retry) fails with this error:
Request did not complete within rpc_timeout
The question
I assume the cluster needs some time to propagate the creation of the table or something like that? If I wait a few seconds between the creation of the table and the retry of the select statement everything works, but I want to know exactly why and if there is a better way of doing it. Perhaps making the create table wait for the changes to propagate before returning?, is there a way of doing that?
Thanks in advance
I am assuming you are using cqlsh. Default consistency level for cqlsh is one meaning it will return after the first node completes but not necessarily before all nodes complete. If you read you aren't guaranteed to read from the node that has the completed table. You can check this by turning on tracing but that will affect performance.
You can enforce consistency which should make that create wait until the table is created on all nodes.
CREATE TABLE ... USING CONSISTENCY ALL

Categories