\set ON_ERROR_STOP

create or replace function simple_file_exists(filename text) returns boolean as $$
     import os.path
     return os.path.isfile(filename)
$$ language plpythonu;

create or replace function move_file(source text, target text) returns void as $$
     import shutil
     shutil.move(source,target)
$$ language plpythonu;

create or replace function copy_file(source text, target text) returns void as $$
     import shutil
     shutil.copy(source,target)
$$ language plpythonu;

create or replace function link_file(source text, target text) returns void as $$
    import os
    os.symlink(source,target)
$$ language plpythonu;

create or replace function unlink_file(filename text) returns void as $$
    import os
    os.unlink(filename)
$$ language plpythonu;

create or replace function chmod_file
(filename text, ownerp integer, groupp integer, worldp integer)
returns void as $$
    import os
    os.chmod(filename, 0100*ownerp + 010*groupp + worldp)
$$ language plpythonu;

create or replace function join_path(path1 text, path2 text) returns text as $$
    import os.path
    return os.path.join(path1,path2)
$$ language plpythonu;    

create or replace function unique_name(pathname text, len integer) returns text as $$
    import os.path
    import random
    while True:
         s = ''
         for i in range(len):
              s += random.choice('ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwxyz0123456789')
         if not(os.path.exists(os.path.join(pathname,s))):
              return s
$$ language plpythonu;

create or replace function unique_name(len integer) returns text as $$
    import os.path
    import random
    s = ''
    for i in range(len):
        s += random.choice('ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwxyz0123456789')
    return s
$$ language plpythonu;

create or replace function path_basename (filepath text) returns text as $$
     import os.path
     return os.path.basename(filepath)
$$ language plpythonu;

