How to add indexes if they do not already exist
See original GitHub issueHi Tim,
I’ve been trying to add indexes to existing columns in postgres database.
I think I found a way to add them using (I found this documented in the knex source):
table.index('column_name')
The problem is that the indexes may already exist in which case I get the following error:
Error: model ensureSchema { [error: relation "models_column_name_index" already exists]
name: 'error',
length: 104,
severity: 'ERROR',
code: '42P07',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
file: 'index.c',
line: '777',
routine: 'index_create' }
I’ve been working at trying to do this for around 6 hours using the Knex.schema.table(table_name, (table) -> ).exec(callback)
inner block and feel like I must be missing something. I originally tried to find a way to get access to a column builder, but I couldn’t use the table.type(column_name).index()
syntax because the column already existed and even if it did, I assume that I would get the same index already existing error.
Is there a lower level way to check for indexes existing? Ideally, it would be general purpose enough that you could check if a column was indexed, primary, nullable, unique, etc.
Thank you in advance for any advice and pseudo code.
Issue Analytics
- State:
- Created 9 years ago
- Comments:12 (6 by maintainers)
Top GitHub Comments
I agree, this is highly unintuitive. The docs seem to imply that the callback is only being called if the table did not exist, so it can be created; otherwise, why would you need to call the table creation API anyway?
I also expected that
knex.schema.createTableIfNotExists
doesn’t run the callback if the table already exists. So the official workaround is to check withhasTable
beforehand?