barannikovav / Paper-storage

The project of data base storage for scientific papers.
MIT License
0 stars 0 forks source link

Check if table already exists in schema #1

Open pavel-collab opened 1 month ago

pavel-collab commented 1 month ago

The current content in schema.sql looks pretty cool, but I think we should to add checking if each table already exists before create it. I prevent some kind of errors if file will be executed several times. To check if some table exist we have to write a condition in SQL command, smth like

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))

CREATE TABLE ...

https://stackoverflow.com/questions/5952006/check-if-table-exists-and-if-it-doesnt-exist-create-it-in-sql-server-2008

In postgresql we can find all of the databases and tables name in system table pg_database, but I don't know what we have to check in MySQL or SQLite. And also, I think we should to incapsulate each table creation in separate transaction. Transaction started with keyword BEGIN and end with key word COMMIT.

pavel-collab commented 1 month ago

You can do smth like that: DROP TABLE IF EXISTS table_name CASCADE;

but in some cases we can remove valuable content by this action, so we should think how to use it perfectly.

barannikovav commented 3 weeks ago

Regarding the issue with redundant table creation. Docs proposes using such command to avoid it:

CREATE TABLE IF NOT EXISTS ...

I want to correct code to this approach in next commit.

Second question is about transactions with table creation. According to docs:

Any command that accesses the database (basically, any SQL command, except a few [PRAGMA] will automatically start a transaction if one is not already in effect. Automatically started transactions are committed when the last SQL statement finishes.

So, I think explicit transaction calls here are excessive.