Revision 2688
Added by Aaron Marcuse-Kubitza over 12 years ago
lib/sql.py | ||
---|---|---|
835 | 835 |
|
836 | 836 |
row_num_col = '_row_num' |
837 | 837 |
|
838 |
def add_index(db, expr): |
|
839 |
'''Adds an index on a column or expression if it doesn't already exist.
|
|
838 |
def add_index(db, exprs, table=None, unique=False):
|
|
839 |
'''Adds an index on column(s) or expression(s) if it doesn't already exist.
|
|
840 | 840 |
Currently, only function calls are supported as expressions. |
841 | 841 |
''' |
842 |
expr = copy.deepcopy(expr) # don't modify input!
|
|
842 |
if not lists.is_seq(exprs): exprs = [exprs]
|
|
843 | 843 |
|
844 |
# Extract col |
|
845 |
if isinstance(expr, sql_gen.FunctionCall): |
|
846 |
col = expr.args[0] |
|
847 |
expr = sql_gen.Expr(expr) |
|
848 |
else: col = expr |
|
849 |
assert sql_gen.is_table_col(col) |
|
844 |
# Parse exprs |
|
845 |
old_exprs = exprs[:] |
|
846 |
exprs = [] |
|
847 |
cols = [] |
|
848 |
for i, expr in enumerate(old_exprs): |
|
849 |
expr = copy.deepcopy(expr) # don't modify input! |
|
850 |
expr = sql_gen.as_Col(expr) |
|
851 |
|
|
852 |
# Extract col |
|
853 |
if isinstance(expr, sql_gen.FunctionCall): |
|
854 |
col = expr.args[0] |
|
855 |
expr = sql_gen.Expr(expr) |
|
856 |
else: col = expr |
|
857 |
|
|
858 |
# Extract table |
|
859 |
if table == None: |
|
860 |
assert sql_gen.is_table_col(col) |
|
861 |
table = col.table |
|
862 |
|
|
863 |
col.table = None |
|
864 |
|
|
865 |
exprs.append(expr) |
|
866 |
cols.append(col) |
|
850 | 867 |
|
851 |
index = sql_gen.as_Table(str(expr)) |
|
852 |
table = col.table |
|
853 |
col.table = None |
|
854 |
try: run_query(db, 'CREATE INDEX '+index.to_str(db)+' ON '+table.to_str(db) |
|
855 |
+' ('+expr.to_str(db)+')', recover=True, cacheable=True, log_level=3) |
|
868 |
table = sql_gen.as_Table(table) |
|
869 |
index = sql_gen.Table(str(sql_gen.Col(','.join(map(str, cols)), table))) |
|
870 |
|
|
871 |
str_ = 'CREATE' |
|
872 |
if unique: str_ += ' UNIQUE' |
|
873 |
str_ += ' INDEX '+index.to_str(db)+' ON '+table.to_str(db)+' ('+( |
|
874 |
', '.join((v.to_str(db) for v in exprs)))+')' |
|
875 |
|
|
876 |
try: run_query(db, str_, recover=True, cacheable=True, log_level=3) |
|
856 | 877 |
except DuplicateTableException: pass # index already existed |
857 | 878 |
|
858 | 879 |
def add_pkey(db, table, cols=None, recover=None): |
Also available in: Unified diff
sql.py: add_index(): Support multiple column(s) or expression(s). Support separate table (not extracted from cols). Support UNIQUE indexes.