query.py 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
from zephir.i18n import _
from json import dumps
from .error import ServerSelectionEmptyRecordDatabaseError

"""
List all serverselections
"""

FETCH_ALL_SERVERSELECTIONS = '''
    SELECT serverselectionid, serverselectionname, serverselectiondescription, serverselectionserversid, serverselectionusers, dynamique, requete
    FROM serverselection
 '''

"""
Fetch one serverselection based on its ID
"""
FETCH_SERVERSELECTION = '''
    SELECT serverselectionid, serverselectionname, serverselectiondescription, serverselectionserversid, serverselectionusers, dynamique, requete
    FROM serverselection
    WHERE serverselectionid = %s
'''

"""
Fetch all serverselection of a user
"""
FETCH_ALL_USER_SERVERSELECTIONS = '''
    SELECT serverselectionid, serverselectionname, serverselectiondescription, serverselectionserversid, serverselectionusers, dynamique, requete
    FROM serverselection
    WHERE exist(serverselectionusers, %s)
 '''
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
"""
Fetch the default serverselection of a user
"""
FETCH_DEFAULT_USER_SERVERSELECTION = '''
    SELECT serverselectionid, serverselectionname, serverselectiondescription, serverselectionserversid, serverselectionusers, dynamique, requete
    FROM serverselection
    WHERE exist(serverselectionusers, %s) AND serverselectionname LIKE %s
 '''

"""
Creates a serverselection based on its name and serverselectionparent
"""
SERVERSELECTION_INSERT = '''
    INSERT INTO serverselection (serverselectionname, serverselectiondescription, serverselectionusers)
    VALUES (%s, %s, %s)
    RETURNING *
'''

"""
Updates a serverselection name based on its ID
"""
SERVERSELECTION_UPDATE = '''
    UPDATE serverselection
    SET serverselectionname = %s,
        serverselectiondescription = %s,
        dynamique = %s,
        requete = %s
    WHERE serverselectionid = %s
    RETURNING *
'''

"""
Deletes a serverselection based on its ID
"""
SERVERSELECTION_DELETE = '''
    DELETE
    FROM serverselection
    WHERE serverselectionid = %s
    RETURNING *
'''

"""
Add a server to a serverselection by its serverid
"""
SERVERSELECTION_ADD_SERVER = '''
    UPDATE serverselection
    SET serverselectionserversid = array_append(serverselectionserversid, %s)
    WHERE serverselectionid = %s
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
80
    AND NOT (%s = ANY (serverselectionserversid))
81 82 83 84 85 86 87 88 89 90 91 92
    RETURNING *
'''

"""
Remove a server from a serverselection
"""
SERVERSELECTION_REMOVE_SERVER = '''
    UPDATE serverselection
    SET serverselectionserversid = array_remove(serverselectionserversid, %s)
    WHERE serverselectionid = %s
    RETURNING *
'''
93 94 95 96 97 98 99 100 101
"""
Remove a server from all the serverselections
"""
SERVERSELECTION_REMOVE_SERVER_FROM_ALL = '''
    UPDATE serverselection
    SET serverselectionserversid = array_remove(serverselectionserversid, %s)
    RETURNING *
'''

Matthieu Lamalle's avatar
Matthieu Lamalle committed
102 103 104 105 106 107 108 109 110
"""
Set a servers list in a serverselection
"""
SERVERSELECTION_SET_SERVER_LIST = '''
    UPDATE serverselection
    SET serverselectionserversid = %s
    WHERE serverselectionid = %s
    RETURNING *
'''
111 112


113 114

"""
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
115
Add User and Role to serverselection
116 117 118 119 120 121 122 123 124
"""
SERVERSELECTION_ADD_USER = '''
    UPDATE serverselection
    SET serverselectionusers = serverselectionusers || %s
    WHERE serverselectionid = %s
    RETURNING *
'''

"""
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
125
Remove User from serverselection
126 127 128 129 130 131 132 133 134
"""
SERVERSELECTION_REMOVE_USER = '''
    UPDATE serverselection
    SET serverselectionusers = delete(serverselectionusers, %s)
    WHERE serverselectionid = %s
    RETURNING *
'''

"""
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
135
Update User's Role from serverselection
136 137 138 139 140 141 142 143
"""
SERVERSELECTION_UPDATE_USER = '''
    UPDATE serverselection
    SET serverselectionusers = serverselectionusers || %s
    WHERE serverselectionid = %s
    RETURNING *
'''

Matthieu Lamalle's avatar
Matthieu Lamalle committed
144 145 146
"""
List all serverselection of a user
"""
147 148 149 150 151
SERVERSELECTION_USER_SERVER_LIST = '''
    SELECT json_agg(c) AS serverselectionserversid
    FROM (
        SELECT DISTINCT unnest(serverselectionserversid)
        FROM serverselection
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
152
        WHERE exist(serverselectionusers, %s))
153 154 155 156 157 158 159 160 161 162
    AS dt(c)
'''

"""
Fetch the user's role of a serverselection
"""
FETCH_ROLE_USER_SERVERSELECTION = '''
    SELECT serverselectionid, serverselectionusers->%s AS role
    FROM serverselection
    WHERE serverselectionid = %s
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
163
    AND serverselectionusers->%s IS NOT NULL
164 165 166 167 168 169 170 171 172
 '''

"""
Fetch the user's role of a server
"""
FETCH_ROLE_USER_SERVER_SERVERSELECTION = '''
    SELECT serverselectionid, serverselectionusers->%s AS role
    FROM serverselection
    WHERE %s = ANY(serverselectionserversid)
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
173
    AND serverselectionusers->%s IS NOT NULL
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
 '''

"""
Suppression du contenu de la table de serverselection
"""
SERVERSELECTION_ERASE = """DELETE from serverselection"""


def fetchone(cursor, query: str, query_parameters: tuple=None, raises: bool=False):
    cursor.execute(query, query_parameters)
    fetched = cursor.fetchone()
    if not fetched:
        if raises:
            raise ServerSelectionEmptyRecordDatabaseError(_("cannot find element with query {} and parameters {}").format(query, query_parameters))
        fetched = None
    return fetched


def serverselection_row_to_dict(serverselection):
    try:
        serverselection_obj = {'serverselectionid': serverselection['serverselectionid'],
                  'serverselectionname': serverselection['serverselectionname'],
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
196
                  'serverselectiondescription': serverselection['serverselectiondescription']}
197 198 199 200 201 202 203 204 205
        if serverselection['serverselectionserversid'] is not None:
            serverselection_obj['serverselectionserversid'] = serverselection['serverselectionserversid']
        if serverselection['serverselectionusers'] is not None:
            serverselection_obj['serverselectionusers'] = parse_numeric_value_hstore(serverselection['serverselectionusers'])
        if serverselection['dynamique'] is not None:
            serverselection_obj['dynamique'] = serverselection['dynamique']
        if serverselection['requete'] is not None:
            serverselection_obj['requete'] = serverselection['requete']
    except KeyError:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
206 207
        serverselection_obj = {}
        raise(ServerSelectionEmptyRecordDatabaseError('No ServerSelection found'))
208 209
    return serverselection_obj

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
210 211 212 213
def serverselection_serversid_dict(serverselection):
    serverselection_obj = {}
    if serverselection['serverselectionserversid'] is not None:
        serverselection_obj['serverselectionserversid'] = serverselection['serverselectionserversid']
214 215
    return serverselection_obj

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
216
def serverselection_role_dict(serverselection, serverselectionuser):
217 218
    try:
        serverselection_obj = {'serverselectionid': serverselection['serverselectionid'],
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
219
                        'username': serverselectionuser}
220 221 222
        if serverselection['role'] is not None:
            serverselection_obj['role'] = serverselection['role']
    except KeyError:
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
223 224
        serverselection_obj = {}
        raise(ServerSelectionEmptyRecordDatabaseError('No ServerSelection found'))
225 226 227
    return serverselection_obj

def fetch_serverselection_user_role(cursor, serverselectionuser, serverselectionid):
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
228
    return serverselection_role_dict(fetchone(cursor, FETCH_ROLE_USER_SERVERSELECTION, (serverselectionuser, serverselectionid, serverselectionuser), raises=True), serverselectionuser)
229 230

def fetch_serverselection_user_server_role(cursor, serverselectionuser, serverid):
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
231
    cursor.execute(FETCH_ROLE_USER_SERVER_SERVERSELECTION, (serverselectionuser, serverid, serverselectionuser))
232 233 234 235 236 237 238 239
    ret = []
    for serverselection in cursor.fetchall():
        ret.append(serverselection_role_dict(serverselection, serverselectionuser))
    return ret

def list_all_serverselections(cursor):
    cursor.execute(FETCH_ALL_SERVERSELECTIONS)
    ret = []
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
240
    for serverselection in cursor.fetchall():
241 242 243
        ret.append(serverselection_row_to_dict(serverselection))
    return ret

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
244
def fetch_serverselection_dict(cursor, serverselectionid):
245
    return serverselection_row_to_dict(fetchone(cursor, FETCH_SERVERSELECTION, (serverselectionid,), raises=True))
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
def fetch_serverselection(cursor, serverselectionid):
    fetched = fetchone(cursor, FETCH_SERVERSELECTION, (serverselectionid,))
    if fetched is None:
        raise Exception(_('unable to find a serverselection with id {}').format(serverselectionid))
    return fetched

def fetch_all_user_serverselections(cursor, serverselectionuser):
    cursor.execute(FETCH_ALL_USER_SERVERSELECTIONS, (serverselectionuser,))
    ret = []
    for serverselection in cursor.fetchall():
        ret.append(serverselection_row_to_dict(serverselection))
    return ret

def fetch_default_user_serverselection(cursor, serverselectionuser):
    userdefault = serverselectionuser+"_DEFAULT"
    try:
        fetched = fetchone(cursor, FETCH_DEFAULT_USER_SERVERSELECTION, (serverselectionuser, userdefault), raises=True)
    except ServerSelectionEmptyRecordDatabaseError:
        fetched = {}
    return serverselection_row_to_dict(fetched)

def fetch_all_user_servers(cursor, serverselectionuser):
    return serverselection_serversid_dict(fetchone(cursor, SERVERSELECTION_USER_SERVER_LIST, (serverselectionuser,), raises=True))

Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
271 272

def insert_serverselection(cursor, serverselectionname, serverselectiondescription, serverselectionuser):
273 274 275 276 277 278 279 280 281 282
    serverselectionuserrolehstore = serverselectionuser + '=>"owner"'
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_INSERT, (serverselectionname, serverselectiondescription, serverselectionuserrolehstore), raises=True))

def update_serverselection(cursor, serverselectionid, serverselectionname, serverselectiondescription, dynamique, requete):
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_UPDATE, (serverselectionname, serverselectiondescription, dynamique, requete, serverselectionid), raises=True))

def delete_serverselection(cursor, serverselectionid):
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_DELETE, (serverselectionid,), raises=True))

def add_server_to_serverselection(cursor, serverselectionserversid, serverselectionid):
Matthieu Lamalle's avatar
Acl  
Matthieu Lamalle committed
283
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_ADD_SERVER, (serverselectionserversid, serverselectionid, serverselectionserversid), raises=True))
284 285 286 287

def remove_server_from_serverselection(cursor, serverselectionserversid, serverselectionid):
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_REMOVE_SERVER, (serverselectionserversid, serverselectionid), raises=True))

288 289 290
def remove_server_from_all_serverselections(cursor, serverselectionserversid ):
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_REMOVE_SERVER_FROM_ALL, (serverselectionserversid,), raises=True))

Matthieu Lamalle's avatar
Matthieu Lamalle committed
291 292 293
def set_list_server_serverselection(cursor, serverselectionid, serveridlist):
    serveridlist = '{'+serveridlist+'}'
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_SET_SERVER_LIST, (serveridlist,serverselectionid), raises=True))
294

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
def add_user_to_serverselection(cursor, serverselectionid, username, role):
    serverselectionuserrolehstore = username + '=>' + role
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_ADD_USER, (serverselectionuserrolehstore, serverselectionid), raises=True))

def remove_user_from_serverselection(cursor, serverselectionid, username):
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_REMOVE_USER, (username, serverselectionid), raises=True))

def update_user_from_serverselection(cursor, serverselectionid, username, role):
    serverselectionuserrolehstore = username + '=>' + role
    return serverselection_row_to_dict(fetchone(cursor, SERVERSELECTION_UPDATE_USER, (serverselectionuserrolehstore, serverselectionid), raises=True))

def erase_serverselection(cursor):
    """
    Supprime le contenu de la table Serverselection
    """
    cursor.execute(SERVERSELECTION_ERASE)


def parse_numeric_value_hstore(string):
    if not string:
        return {}
    tmp = string.replace('"',"").split(",")
    res = {}
    for i in tmp:
        key, value = map(str.strip, i.split("=>"))
        res[key] = value
    return res


def dict_to_hstore_text(dic):
    res = ''
    for key, value in dic.items():
        res += '"{}"=>"{}",'.format(key, value)
    if res:
        res = res[:-1]
    return res