Delete app
Browse filesFiles changed (5)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677package database
import ( "log" "os" "path/filepath" "time"
"github.com/divyam234/teldrive/utils" "github.com/pressly/goose/v3" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" "gorm.io/gorm/schema")
var DB *gorm.DB
func InitDB() {
var err error
newLogger := logger.New( log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: time.Second, LogLevel: logger.Silent, IgnoreRecordNotFoundError: true, ParameterizedQueries: true, Colorful: false, }, )
DB, err = gorm.Open(postgres.Open(utils.GetConfig().DatabaseUrl), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: "teldrive.", SingularTable: false, }, PrepareStmt: false, NowFunc: func() time.Time { return time.Now().UTC() }, Logger: newLogger, }) if err != nil { panic(err) }
sqlDB, err := DB.DB() if err != nil { panic(err) } sqlDB.SetMaxIdleConns(10) sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour) go func() { DB.Exec(`create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');`) if utils.GetConfig().RunMigrations { migrate() } }()
}
func migrate() {
config := utils.GetConfig()
if err := goose.SetDialect("postgres"); err != nil { panic(err) } db, _ := DB.DB() if err := goose.Up(db, filepath.Join(config.ExecDir, "database", "migrations")); err != nil { panic(err) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566-- +goose Upcreate extension if not exists pgcrypto;
create extension if not exists btree_gin;
create schema if not exists teldrive;
create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');
-- +goose StatementBegincreate or replacefunction teldrive.generate_uid(size int) returns text language plpgsql as $$declare characters text := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
bytes bytea := gen_random_bytes(size);
l int := length(characters);
i int := 0;
output text := '';
begin while i < size loop output := output || substr(characters,get_byte(bytes,i) % l + 1,1);
i := i + 1;end loop;
return output;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate or replacefunction teldrive.get_tsvector(t text) returns tsvector language plpgsql immutable as $$declare res tsvector := to_tsvector(regexp_replace(t,'[^A-Za-z0-9 ]',' ','g'));
begin return res;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate or replacefunction teldrive.get_tsquery(t text) returns tsquery language plpgsql immutable as $$declare res tsquery = concat(plainto_tsquery(regexp_replace(t,'[^A-Za-z0-9 ]',' ','g')),':*')::tsquery;
begin return res;end;
$$;-- +goose StatementEnd12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788-- +goose Upcreate table teldrive.files (id text primary key not null default teldrive.generate_uid(16),name text not null,type text not null,mime_type text not null,path text null,size bigint null,starred bool not null,depth integer null,user_id bigint not null,parent_id text null,status text default 'active'::text,channel_id bigint null,parts jsonb null,created_at timestamp not null default timezone('utc'::text,now()),updated_at timestamp not null default timezone('utc'::text,now()),constraint unique_file unique (name,parent_id,user_id));
create table teldrive.uploads ( id text not null primary key default teldrive.generate_uid(16), upload_id text not null, name text not null, part_no int4 not null, part_id int4 not null, total_parts int4 not null, channel_id int8 not null, size int8 not null, created_at timestamp null default timezone('utc'::text,now()));
create table teldrive.users ( user_id bigint not null primary key, name text null, user_name text null, is_premium bool not null, tg_session text not null, settings jsonb null, created_at timestamptz not null default timezone('utc'::text,now()), updated_at timestamptz not null default timezone('utc'::text,now()));
create collation if not exists numeric (provider = icu, locale = 'en@colnumeric=yes');create index name_search_idx onteldrive.files using gin (teldrive.get_tsvector(name),updated_at);
create index name_numeric_idx onteldrive.files(name collate numeric nulls first);
create index parent_name_numeric_idx onteldrive.files (parent_id,name collate numeric desc);
create index path_idx onteldrive.files (path);
create index parent_idx onteldrive.files (parent_id);
create index starred_updated_at_idx onteldrive.files (starred,updated_at desc);
create index status_idx on teldrive.files (status);
create index user_id_idx on teldrive.files (user_id);
-- +goose Downdrop table if exists teldrive.files;drop table if exists teldrive.uploads;drop table if exists teldrive.users;drop index if exists teldrive.name_search_idx;drop index if exists teldrive.name_numeric_idx;drop index if exists teldrive.parent_name_numeric_idx;drop index if exists teldrive.path_idx;drop index if exists teldrive.parent_idx;drop index if exists teldrive.starred_updated_at_idx;drop index if exists teldrive.status_idx;drop index if exists teldrive.user_id_idx;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188-- +goose Up
-- +goose StatementBegincreate procedure teldrive.update_size() language plpgsql as $$declare rec record;
total_size bigint;
begin
for rec inselect idfrom fileswhere type = 'folder'order by depth desc loop total_size := ( select sum(size) as total_size from teldrive.files where parent_id = rec.id);
update teldrive.filesset size = total_sizewhere id = rec.id;end loop;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate function teldrive.update_folder(folder_id text,new_name text default null,new_path text default null) returns setof teldrive.files language plpgsqlas $$declare folder record;
path_items text [];
begin
if new_path is null thenselect *into folderfrom teldrive.fileswhere id = folder_id;
path_items := string_to_array(folder.path,'/');
path_items [array_length(path_items,1)] := new_name;
new_path := array_to_string(path_items,'/');end if;
update teldrive.filesset path = new_path, name = new_namewhere id = folder_id;
for folder inselect *from teldrive.fileswhere type = 'folder' and parent_id = folder_id loop call teldrive.update_folder( folder.id, folder.name, concat(new_path, '/', folder.name));end loop;
return queryselect *from teldrive.fileswhere id = folder_id;end;
$$;-- +goose StatementEnd
-- +goose StatementBegincreate procedure teldrive.delete_files(in file_ids text[],in op text default 'bulk') language plpgsqlas $$ declare rec record;
begin if op = 'bulk' then for rec inselect id, typefrom teldrive.fileswhere id = any (file_ids) loop if rec.type = 'folder' then call teldrive.delete_files(array [rec.id], 'single');
deletefrom teldrive.fileswhere id = rec.id;else update teldrive.filesset status = 'pending_deletion'where id = rec.id;end if;end loop;else for rec inselect id, typefrom teldrive.fileswhere parent_id = file_ids[1] loop if rec.type = 'folder' then call teldrive.delete_files(array [rec.id], 'single');
deletefrom teldrive.fileswhere id = rec.id;else update teldrive.filesset status = 'pending_deletion'where id = rec.id;end if;end loop;end if;end;
$$;-- +goose StatementEnd
-- +goose Downdrop procedure if exists teldrive.update_size;drop function if exists teldrive.update_folder;drop procedure if exists teldrive.delete_files;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748-- +goose Up-- +goose StatementBegin
CREATE OR REPLACE FUNCTION teldrive.create_directories( IN tg_id BIGINT, IN long_path TEXT) RETURNS SETOF teldrive.files AS $$DECLARE path_parts TEXT[]; current_directory_id TEXT; new_directory_id TEXT; directory_name TEXT; path_so_far TEXT; depth_dir integer;begin path_parts := string_to_array(regexp_replace(long_path, '^/+', ''), '/'); path_so_far := ''; depth_dir := 0;
SELECT id into current_directory_id FROM teldrive.files WHERE parent_id='root';
FOR directory_name IN SELECT unnest(path_parts) LOOP path_so_far := CONCAT(path_so_far,'/', directory_name); depth_dir := depth_dir +1; SELECT id INTO new_directory_id FROM teldrive.files WHERE parent_id = current_directory_id AND "name" = directory_name AND "user_id"=tg_id;
IF new_directory_id IS NULL THEN INSERT INTO teldrive.files ("name", "type", mime_type, parent_id, "user_id",starred,"depth","path") VALUES (directory_name, 'folder', 'drive/folder', current_directory_id, tg_id,false,depth_dir,path_so_far) RETURNING id INTO new_directory_id; END IF; current_directory_id := new_directory_id; END LOOP;
RETURN QUERY SELECT * FROM teldrive.files WHERE id = current_directory_id;END;$$ LANGUAGE plpgsql;-- +goose StatementEnd
-- +goose DownDROP FUNCTION IF EXISTS teldrive.create_directories;app/database/database.goDeleted-77
app/database/migrations/20230817172319_init.sqlDeleted-66
app/database/migrations/20230817172325_tables.sqlDeleted-88
app/database/migrations/20230817172329_functions.sqlDeleted-188
app/database/migrations/20230820014560_create_dirs_from_path.sqlDeleted-48