-
Notifications
You must be signed in to change notification settings - Fork 2k
/
postgres.py
1970 lines (1646 loc) · 67 KB
/
postgres.py
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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import copy
import logging
import sys
import sqlalchemy
import os
import pprint
import sqlalchemy.engine.url as sa_url
import urllib
import urllib2
import urlparse
import datetime
import hashlib
import json
from cStringIO import StringIO
from six import string_types, text_type
import ckan.lib.cli as cli
import ckan.plugins as p
import ckan.plugins.toolkit as toolkit
from ckan.lib.lazyjson import LazyJSONObject
import ckanext.datastore.helpers as datastore_helpers
import ckanext.datastore.interfaces as interfaces
from psycopg2.extras import register_default_json, register_composite
import distutils.version
from sqlalchemy.exc import (ProgrammingError, IntegrityError,
DBAPIError, DataError)
import ckan.model as model
import ckan.plugins as plugins
from ckan.common import config, OrderedDict
from ckanext.datastore.backend import (
DatastoreBackend,
DatastoreException,
_parse_sort_clause
)
from ckanext.datastore.backend import InvalidDataError
log = logging.getLogger(__name__)
_pg_types = {}
_type_names = set()
_engines = {}
_TIMEOUT = 60000 # milliseconds
# See http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
_PG_ERR_CODE = {
'unique_violation': '23505',
'query_canceled': '57014',
'undefined_object': '42704',
'syntax_error': '42601',
'permission_denied': '42501',
'duplicate_table': '42P07',
'duplicate_alias': '42712',
}
_DATE_FORMATS = ['%Y-%m-%d',
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%dT%H:%M:%S',
'%Y-%m-%dT%H:%M:%SZ',
'%d/%m/%Y',
'%m/%d/%Y',
'%d-%m-%Y',
'%m-%d-%Y']
_INSERT = 'insert'
_UPSERT = 'upsert'
_UPDATE = 'update'
if not os.environ.get('DATASTORE_LOAD'):
ValidationError = toolkit.ValidationError
else:
log.warn("Running datastore without CKAN")
class ValidationError(Exception):
def __init__(self, error_dict):
pprint.pprint(error_dict)
is_single_statement = datastore_helpers.is_single_statement
_engines = {}
def literal_string(s):
"""
Return s as a postgres literal string
"""
return u"'" + s.replace(u"'", u"''").replace(u'\0', '') + u"'"
def identifier(s):
"""
Return s as a quoted postgres identifier
"""
return u'"' + s.replace(u'"', u'""').replace(u'\0', '') + u'"'
def get_read_engine():
return _get_engine_from_url(config['ckan.datastore.read_url'])
def get_write_engine():
return _get_engine_from_url(config['ckan.datastore.write_url'])
def _get_engine_from_url(connection_url):
'''Get either read or write engine.'''
engine = _engines.get(connection_url)
if not engine:
extras = {'url': connection_url}
engine = sqlalchemy.engine_from_config(config,
'ckan.datastore.sqlalchemy.',
**extras)
_engines[connection_url] = engine
# don't automatically convert to python objects
# when using native json types in 9.2+
# http://initd.org/psycopg/docs/extras.html#adapt-json
register_default_json(conn_or_curs=engine.raw_connection().connection,
globally=False,
loads=lambda x: x)
return engine
def _dispose_engines():
'''Dispose all database engines.'''
global _engines
for url, engine in _engines.items():
engine.dispose()
_engines = {}
def _pluck(field, arr):
return [x[field] for x in arr]
def _rename_json_field(data_dict):
'''Rename json type to a corresponding type for the datastore since
pre 9.2 postgres versions do not support native json'''
return _rename_field(data_dict, 'json', 'nested')
def _unrename_json_field(data_dict):
return _rename_field(data_dict, 'nested', 'json')
def _rename_field(data_dict, term, replace):
fields = data_dict.get('fields', [])
for i, field in enumerate(fields):
if 'type' in field and field['type'] == term:
data_dict['fields'][i]['type'] = replace
return data_dict
def _get_fields_types(context, data_dict):
all_fields = _get_fields(context, data_dict)
all_fields.insert(0, {'id': '_id', 'type': 'int'})
field_types = OrderedDict([(f['id'], f['type']) for f in all_fields])
return field_types
def _get_type(context, oid):
_cache_types(context)
return _pg_types[oid]
def _guess_type(field):
'''Simple guess type of field, only allowed are
integer, numeric and text'''
data_types = set([int, float])
if isinstance(field, (dict, list)):
return 'nested'
if isinstance(field, int):
return 'int'
if isinstance(field, float):
return 'float'
for data_type in list(data_types):
try:
data_type(field)
except (TypeError, ValueError):
data_types.discard(data_type)
if not data_types:
break
if int in data_types:
return 'integer'
elif float in data_types:
return 'numeric'
# try iso dates
for format in _DATE_FORMATS:
try:
datetime.datetime.strptime(field, format)
return 'timestamp'
except (ValueError, TypeError):
continue
return 'text'
def _get_unique_key(context, data_dict):
sql_get_unique_key = '''
SELECT
a.attname AS column_names
FROM
pg_class t,
pg_index idx,
pg_attribute a
WHERE
t.oid = idx.indrelid
AND a.attrelid = t.oid
AND a.attnum = ANY(idx.indkey)
AND t.relkind = 'r'
AND idx.indisunique = true
AND idx.indisprimary = false
AND t.relname = %s
'''
key_parts = context['connection'].execute(sql_get_unique_key,
data_dict['resource_id'])
return [x[0] for x in key_parts]
def _get_field_info(connection, resource_id):
u'''return a dictionary mapping column names to their info data,
when present'''
qtext = sqlalchemy.text(u'''
select pa.attname as name, pd.description as info
from pg_class pc, pg_attribute pa, pg_description pd
where pa.attrelid = pc.oid and pd.objoid = pc.oid
and pd.objsubid = pa.attnum and pc.relname = :res_id
and pa.attnum > 0
''')
try:
return dict(
(n, json.loads(v)) for (n, v) in
connection.execute(qtext, res_id=resource_id).fetchall())
except ValueError: # don't die on non-json comments
return {}
def _get_fields(context, data_dict):
fields = []
all_fields = context['connection'].execute(
u'SELECT * FROM "{0}" LIMIT 1'.format(data_dict['resource_id'])
)
for field in all_fields.cursor.description:
if not field[0].startswith('_'):
fields.append({
'id': field[0].decode('utf-8'),
'type': _get_type(context, field[1])
})
return fields
def _cache_types(context):
if not _pg_types:
connection = context['connection']
results = connection.execute(
'SELECT oid, typname FROM pg_type;'
)
for result in results:
_pg_types[result[0]] = result[1]
_type_names.add(result[1])
if 'nested' not in _type_names:
native_json = _pg_version_is_at_least(connection, '9.2')
log.info("Create nested type. Native JSON: {0!r}".format(
native_json))
backend = DatastorePostgresqlBackend.get_active_backend()
engine = backend._get_write_engine()
with engine.begin() as connection:
connection.execute(
'CREATE TYPE "nested" AS (json {0}, extra text)'.format(
'json' if native_json else 'text'))
_pg_types.clear()
# redo cache types with json now available.
return _cache_types(context)
register_composite('nested', connection.connection, True)
def _pg_version_is_at_least(connection, version):
try:
v = distutils.version.LooseVersion(version)
pg_version = connection.execute('select version();').fetchone()
pg_version_number = pg_version[0].split()[1]
pv = distutils.version.LooseVersion(pg_version_number)
return v <= pv
except ValueError:
return False
def _get_read_only_user(data_dict):
parsed = cli.parse_db_config('ckan.datastore.read_url')
return parsed['db_user']
def _is_array_type(field_type):
return field_type.startswith('_')
def _validate_record(record, num, field_names):
# check record for sanity
if not isinstance(record, dict):
raise ValidationError({
'records': [u'row "{0}" is not a json object'.format(num)]
})
# check for extra fields in data
extra_keys = set(record.keys()) - set(field_names)
if extra_keys:
raise ValidationError({
'records': [u'row "{0}" has extra keys "{1}"'.format(
num + 1,
', '.join(list(extra_keys))
)]
})
def _where_clauses(data_dict, fields_types):
filters = data_dict.get('filters', {})
clauses = []
for field, value in filters.iteritems():
if field not in fields_types:
continue
field_array_type = _is_array_type(fields_types[field])
if isinstance(value, list) and not field_array_type:
clause_str = (u'"{0}" in ({1})'.format(field,
','.join(['%s'] * len(value))))
clause = (clause_str,) + tuple(value)
else:
clause = (u'"{0}" = %s'.format(field), value)
clauses.append(clause)
# add full-text search where clause
q = data_dict.get('q')
if q:
if isinstance(q, string_types):
ts_query_alias = _ts_query_alias()
clause_str = u'_full_text @@ {0}'.format(ts_query_alias)
clauses.append((clause_str,))
elif isinstance(q, dict):
lang = _fts_lang(data_dict.get('lang'))
for field, value in q.iteritems():
if field not in fields_types:
continue
query_field = _ts_query_alias(field)
ftyp = fields_types[field]
if not datastore_helpers.should_fts_index_field_type(ftyp):
clause_str = u'_full_text @@ {0}'.format(query_field)
clauses.append((clause_str,))
clause_str = (u'to_tsvector({0}, cast("{1}" as text)) '
u'@@ {2}').format(
literal_string(lang),
field, query_field)
clauses.append((clause_str,))
return clauses
def _textsearch_query(data_dict):
q = data_dict.get('q')
lang = _fts_lang(data_dict.get('lang'))
if not q:
return '', ''
statements = []
rank_columns = []
plain = data_dict.get('plain', True)
if isinstance(q, string_types):
query, rank = _build_query_and_rank_statements(
lang, q, plain)
statements.append(query)
rank_columns.append(rank)
elif isinstance(q, dict):
for field, value in q.iteritems():
query, rank = _build_query_and_rank_statements(
lang, value, plain, field)
statements.append(query)
rank_columns.append(rank)
statements_str = ', ' + ', '.join(statements)
rank_columns_str = ', '.join(rank_columns)
return statements_str, rank_columns_str
def _build_query_and_rank_statements(lang, query, plain, field=None):
query_alias = _ts_query_alias(field)
rank_alias = _ts_rank_alias(field)
lang_literal = literal_string(lang)
query_literal = literal_string(query)
if plain:
statement = u"plainto_tsquery({lang_literal}, {literal}) {alias}"
else:
statement = u"to_tsquery({lang_literal}, {literal}) {alias}"
statement = statement.format(
lang_literal=lang_literal,
literal=query_literal, alias=query_alias)
if field is None:
rank_field = '_full_text'
else:
rank_field = u'to_tsvector({lang_literal}, cast("{field}" as text))'
rank_field = rank_field.format(lang_literal=lang_literal, field=field)
rank_statement = u'ts_rank({rank_field}, {query_alias}, 32) AS {alias}'
rank_statement = rank_statement.format(rank_field=rank_field,
query_alias=query_alias,
alias=rank_alias)
return statement, rank_statement
def _fts_lang(lang=None):
default_fts_lang = config.get('ckan.datastore.default_fts_lang')
if default_fts_lang is None:
default_fts_lang = u'english'
return lang or default_fts_lang
def _ts_rank_alias(field=None):
rank_alias = u'rank'
if field:
rank_alias += u' ' + field
return u'"{0}"'.format(rank_alias)
def _sort(data_dict, fields_types):
sort = data_dict.get('sort')
if not sort:
q = data_dict.get('q')
if q:
if isinstance(q, string_types):
return [_ts_rank_alias()]
elif isinstance(q, dict):
return [_ts_rank_alias(field) for field in q
if field not in fields_types]
else:
return []
clauses = datastore_helpers.get_list(sort, False)
clause_parsed = []
for clause in clauses:
field, sort = _parse_sort_clause(clause, fields_types)
clause_parsed.append(
u'{0} {1}'.format(identifier(field), sort))
return clause_parsed
def _ts_query_alias(field=None):
query_alias = u'query'
if field:
query_alias += u' ' + field
return u'"{0}"'.format(query_alias)
def _get_aliases(context, data_dict):
'''Get a list of aliases for a resource.'''
res_id = data_dict['resource_id']
alias_sql = sqlalchemy.text(
u'SELECT name FROM "_table_metadata" WHERE alias_of = :id')
results = context['connection'].execute(alias_sql, id=res_id).fetchall()
return [x[0] for x in results]
def _get_resources(context, alias):
'''Get a list of resources for an alias. There could be more than one alias
in a resource_dict.'''
alias_sql = sqlalchemy.text(
u'''SELECT alias_of FROM "_table_metadata"
WHERE name = :alias AND alias_of IS NOT NULL''')
results = context['connection'].execute(alias_sql, alias=alias).fetchall()
return [x[0] for x in results]
def create_alias(context, data_dict):
aliases = datastore_helpers.get_list(data_dict.get('aliases'))
if aliases is not None:
# delete previous aliases
previous_aliases = _get_aliases(context, data_dict)
for alias in previous_aliases:
sql_alias_drop_string = u'DROP VIEW "{0}"'.format(alias)
context['connection'].execute(sql_alias_drop_string)
try:
for alias in aliases:
sql_alias_string = u'''CREATE VIEW "{alias}"
AS SELECT * FROM "{main}"'''.format(
alias=alias,
main=data_dict['resource_id']
)
res_ids = _get_resources(context, alias)
if res_ids:
raise ValidationError({
'alias': [(u'The alias "{0}" already exists.').format(
alias)]
})
context['connection'].execute(sql_alias_string)
except DBAPIError as e:
if e.orig.pgcode in [_PG_ERR_CODE['duplicate_table'],
_PG_ERR_CODE['duplicate_alias']]:
raise ValidationError({
'alias': [u'"{0}" already exists'.format(alias)]
})
def _generate_index_name(resource_id, field):
value = (resource_id + field).encode('utf-8')
return hashlib.sha1(value).hexdigest()
def _get_fts_index_method():
method = config.get('ckan.datastore.default_fts_index_method')
return method or 'gist'
def _build_fts_indexes(connection, data_dict, sql_index_str_method, fields):
fts_indexes = []
resource_id = data_dict['resource_id']
# FIXME: This is repeated on the plugin.py, we should keep it DRY
default_fts_lang = config.get('ckan.datastore.default_fts_lang')
if default_fts_lang is None:
default_fts_lang = u'english'
fts_lang = data_dict.get('lang', default_fts_lang)
# create full-text search indexes
def to_tsvector(x):
return u"to_tsvector('{0}', {1})".format(fts_lang, x)
def cast_as_text(x):
return u'cast("{0}" AS text)'.format(x)
full_text_field = {'type': 'tsvector', 'id': '_full_text'}
for field in [full_text_field] + fields:
if not datastore_helpers.should_fts_index_field_type(field['type']):
continue
field_str = field['id']
if field['type'] not in ['text', 'tsvector']:
field_str = cast_as_text(field_str)
else:
field_str = u'"{0}"'.format(field_str)
if field['type'] != 'tsvector':
field_str = to_tsvector(field_str)
fts_indexes.append(sql_index_str_method.format(
res_id=resource_id,
unique='',
name=_generate_index_name(resource_id, field_str),
method=_get_fts_index_method(), fields=field_str))
return fts_indexes
def _drop_indexes(context, data_dict, unique=False):
sql_drop_index = u'DROP INDEX "{0}" CASCADE'
sql_get_index_string = u"""
SELECT
i.relname AS index_name
FROM
pg_class t,
pg_class i,
pg_index idx
WHERE
t.oid = idx.indrelid
AND i.oid = idx.indexrelid
AND t.relkind = 'r'
AND idx.indisunique = {unique}
AND idx.indisprimary = false
AND t.relname = %s
""".format(unique='true' if unique else 'false')
indexes_to_drop = context['connection'].execute(
sql_get_index_string, data_dict['resource_id']).fetchall()
for index in indexes_to_drop:
context['connection'].execute(
sql_drop_index.format(index[0]).replace('%', '%%'))
def _get_index_names(connection, resource_id):
sql = u"""
SELECT
i.relname AS index_name
FROM
pg_class t,
pg_class i,
pg_index idx
WHERE
t.oid = idx.indrelid
AND i.oid = idx.indexrelid
AND t.relkind = 'r'
AND t.relname = %s
"""
results = connection.execute(sql, resource_id).fetchall()
return [result[0] for result in results]
def _is_valid_pg_type(context, type_name):
if type_name in _type_names:
return True
else:
connection = context['connection']
try:
connection.execute('SELECT %s::regtype', type_name)
except ProgrammingError as e:
if e.orig.pgcode in [_PG_ERR_CODE['undefined_object'],
_PG_ERR_CODE['syntax_error']]:
return False
raise
else:
return True
def _execute_single_statement(context, sql_string, where_values):
if not datastore_helpers.is_single_statement(sql_string):
raise ValidationError({
'query': ['Query is not a single statement.']
})
results = context['connection'].execute(sql_string, [where_values])
return results
def _insert_links(data_dict, limit, offset):
'''Adds link to the next/prev part (same limit, offset=offset+limit)
and the resource page.'''
data_dict['_links'] = {}
# get the url from the request
try:
urlstring = toolkit.request.environ['CKAN_CURRENT_URL']
except (KeyError, TypeError):
return # no links required for local actions
# change the offset in the url
parsed = list(urlparse.urlparse(urlstring))
query = urllib2.unquote(parsed[4])
arguments = dict(urlparse.parse_qsl(query))
arguments_start = dict(arguments)
arguments_prev = dict(arguments)
arguments_next = dict(arguments)
if 'offset' in arguments_start:
arguments_start.pop('offset')
arguments_next['offset'] = int(offset) + int(limit)
arguments_prev['offset'] = int(offset) - int(limit)
parsed_start = parsed[:]
parsed_prev = parsed[:]
parsed_next = parsed[:]
parsed_start[4] = urllib.urlencode(arguments_start)
parsed_next[4] = urllib.urlencode(arguments_next)
parsed_prev[4] = urllib.urlencode(arguments_prev)
# add the links to the data dict
data_dict['_links']['start'] = urlparse.urlunparse(parsed_start)
data_dict['_links']['next'] = urlparse.urlunparse(parsed_next)
if int(offset) - int(limit) > 0:
data_dict['_links']['prev'] = urlparse.urlunparse(parsed_prev)
def _where(where_clauses_and_values):
'''Return a SQL WHERE clause from list with clauses and values
:param where_clauses_and_values: list of tuples with format
(where_clause, param1, ...)
:type where_clauses_and_values: list of tuples
:returns: SQL WHERE string with placeholders for the parameters, and list
of parameters
:rtype: string
'''
where_clauses = []
values = []
for clause_and_values in where_clauses_and_values:
where_clauses.append('(' + clause_and_values[0] + ')')
values += clause_and_values[1:]
where_clause = u' AND '.join(where_clauses)
if where_clause:
where_clause = u'WHERE ' + where_clause
return where_clause, values
def convert(data, type_name):
if data is None:
return None
if type_name == 'nested':
return json.loads(data[0])
# array type
if type_name.startswith('_'):
sub_type = type_name[1:]
return [convert(item, sub_type) for item in data]
if type_name == 'tsvector':
return text_type(data, 'utf-8')
if isinstance(data, datetime.datetime):
return data.isoformat()
if isinstance(data, (int, float)):
return data
return text_type(data)
def check_fields(context, fields):
'''Check if field types are valid.'''
for field in fields:
if field.get('type') and not _is_valid_pg_type(context, field['type']):
raise ValidationError({
'fields': [u'"{0}" is not a valid field type'.format(
field['type'])]
})
elif not datastore_helpers.is_valid_field_name(field['id']):
raise ValidationError({
'fields': [u'"{0}" is not a valid field name'.format(
field['id'])]
})
def create_indexes(context, data_dict):
connection = context['connection']
indexes = datastore_helpers.get_list(data_dict.get('indexes'))
# primary key is not a real primary key
# it's just a unique key
primary_key = datastore_helpers.get_list(data_dict.get('primary_key'))
sql_index_tmpl = u'CREATE {unique} INDEX "{name}" ON "{res_id}"'
sql_index_string_method = sql_index_tmpl + u' USING {method}({fields})'
sql_index_string = sql_index_tmpl + u' ({fields})'
sql_index_strings = []
fields = _get_fields(context, data_dict)
field_ids = _pluck('id', fields)
json_fields = [x['id'] for x in fields if x['type'] == 'nested']
fts_indexes = _build_fts_indexes(connection,
data_dict,
sql_index_string_method,
fields)
sql_index_strings = sql_index_strings + fts_indexes
if indexes is not None:
_drop_indexes(context, data_dict, False)
else:
indexes = []
if primary_key is not None:
unique_keys = _get_unique_key(context, data_dict)
if sorted(unique_keys) != sorted(primary_key):
_drop_indexes(context, data_dict, True)
indexes.append(primary_key)
for index in indexes:
if not index:
continue
index_fields = datastore_helpers.get_list(index)
for field in index_fields:
if field not in field_ids:
raise ValidationError({
'index': [
u'The field "{0}" is not a valid column name.'.format(
index)]
})
fields_string = u', '.join(
['(("{0}").json::text)'.format(field)
if field in json_fields else
'"%s"' % field
for field in index_fields])
sql_index_strings.append(sql_index_string.format(
res_id=data_dict['resource_id'],
unique='unique' if index == primary_key else '',
name=_generate_index_name(data_dict['resource_id'], fields_string),
fields=fields_string))
sql_index_strings = map(lambda x: x.replace('%', '%%'), sql_index_strings)
current_indexes = _get_index_names(context['connection'],
data_dict['resource_id'])
for sql_index_string in sql_index_strings:
has_index = [c for c in current_indexes
if sql_index_string.find(c) != -1]
if not has_index:
connection.execute(sql_index_string)
def create_table(context, data_dict):
'''Creates table, columns and column info (stored as comments).
:param resource_id: The resource ID (i.e. postgres table name)
:type resource_id: string
:param fields: details of each field/column, each with properties:
id - field/column name
type - optional, otherwise it is guessed from the first record
info - some field/column properties, saved as a JSON string in postgres
as a column comment. e.g. "type_override", "label", "notes"
:type fields: list of dicts
:param records: records, of which the first is used when a field type needs
guessing.
:type records: list of dicts
'''
datastore_fields = [
{'id': '_id', 'type': 'serial primary key'},
{'id': '_full_text', 'type': 'tsvector'},
]
# check first row of data for additional fields
extra_fields = []
supplied_fields = data_dict.get('fields', [])
check_fields(context, supplied_fields)
field_ids = _pluck('id', supplied_fields)
records = data_dict.get('records')
fields_errors = []
for field_id in field_ids:
# Postgres has a limit of 63 characters for a column name
if len(field_id) > 63:
message = 'Column heading "{0}" exceeds limit of 63 '\
'characters.'.format(field_id)
fields_errors.append(message)
if fields_errors:
raise ValidationError({
'fields': fields_errors
})
# if type is field is not given try and guess or throw an error
for field in supplied_fields:
if 'type' not in field:
if not records or field['id'] not in records[0]:
raise ValidationError({
'fields': [u'"{0}" type not guessable'.format(field['id'])]
})
field['type'] = _guess_type(records[0][field['id']])
# Check for duplicate fields
unique_fields = set([f['id'] for f in supplied_fields])
if not len(unique_fields) == len(supplied_fields):
raise ValidationError({
'field': ['Duplicate column names are not supported']
})
if records:
# check record for sanity
if not isinstance(records[0], dict):
raise ValidationError({
'records': ['The first row is not a json object']
})
supplied_field_ids = records[0].keys()
for field_id in supplied_field_ids:
if field_id not in field_ids:
extra_fields.append({
'id': field_id,
'type': _guess_type(records[0][field_id])
})
fields = datastore_fields + supplied_fields + extra_fields
sql_fields = u", ".join([u'{0} {1}'.format(
identifier(f['id']), f['type']) for f in fields])
sql_string = u'CREATE TABLE {0} ({1});'.format(
identifier(data_dict['resource_id']),
sql_fields
)
info_sql = []
for f in supplied_fields:
info = f.get(u'info')
if isinstance(info, dict):
info_sql.append(u'COMMENT ON COLUMN {0}.{1} is {2}'.format(
identifier(data_dict['resource_id']),
identifier(f['id']),
literal_string(
json.dumps(info, ensure_ascii=False))))
context['connection'].execute(
(sql_string + u';'.join(info_sql)).replace(u'%', u'%%'))
def alter_table(context, data_dict):
'''Adds new columns and updates column info (stored as comments).
:param resource_id: The resource ID (i.e. postgres table name)
:type resource_id: string
:param fields: details of each field/column, each with properties:
id - field/column name
type - optional, otherwise it is guessed from the first record
info - some field/column properties, saved as a JSON string in postgres
as a column comment. e.g. "type_override", "label", "notes"
:type fields: list of dicts
:param records: records, of which the first is used when a field type needs
guessing.
:type records: list of dicts
'''
supplied_fields = data_dict.get('fields', [])
current_fields = _get_fields(context, data_dict)
if not supplied_fields:
supplied_fields = current_fields
check_fields(context, supplied_fields)
field_ids = _pluck('id', supplied_fields)
records = data_dict.get('records')
new_fields = []
for num, field in enumerate(supplied_fields):
# check to see if field definition is the same or and
# extension of current fields
if num < len(current_fields):
if field['id'] != current_fields[num]['id']:
raise ValidationError({
'fields': [(u'Supplied field "{0}" not '
u'present or in wrong order').format(
field['id'])]
})
# no need to check type as field already defined.
continue
if 'type' not in field:
if not records or field['id'] not in records[0]:
raise ValidationError({
'fields': [u'"{0}" type not guessable'.format(field['id'])]
})
field['type'] = _guess_type(records[0][field['id']])
new_fields.append(field)
if records:
# check record for sanity as they have not been
# checked during validation
if not isinstance(records, list):
raise ValidationError({
'records': ['Records has to be a list of dicts']
})
if not isinstance(records[0], dict):
raise ValidationError({
'records': ['The first row is not a json object']
})
supplied_field_ids = records[0].keys()
for field_id in supplied_field_ids:
if field_id not in field_ids:
new_fields.append({
'id': field_id,
'type': _guess_type(records[0][field_id])
})
alter_sql = []
for f in new_fields:
alter_sql.append(u'ALTER TABLE {0} ADD {1} {2};'.format(
identifier(data_dict['resource_id']),
identifier(f['id']),
f['type']))
for f in supplied_fields:
if u'info' in f:
info = f.get(u'info')
if isinstance(info, dict):
info_sql = literal_string(
json.dumps(info, ensure_ascii=False))
else:
info_sql = 'NULL'
alter_sql.append(u'COMMENT ON COLUMN {0}.{1} is {2}'.format(
identifier(data_dict['resource_id']),
identifier(f['id']),
info_sql))
if alter_sql:
context['connection'].execute(
u';'.join(alter_sql).replace(u'%', u'%%'))
def insert_data(context, data_dict):
"""
:raises InvalidDataError: if there is an invalid value in the given data
"""
data_dict['method'] = _INSERT
result = upsert_data(context, data_dict)
return result
def upsert_data(context, data_dict):
'''insert all data from records'''
if not data_dict.get('records'):
return
method = data_dict.get('method', _UPSERT)