sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_last(self): """ Get the last migration batch. :rtype: list """ query = self.table().where('batch', self.get_last_batch_number()) return query.order_by('migration', 'desc').get()
Get the last migration batch. :rtype: list
entailment
def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str """ # Essentially we will force every insert to be treated as a batch insert which # simply makes creating the SQL easier for us since we can utilize the same # basic routine regardless of an amount of records given to us to insert. table = self.wrap_table(query.from__) if not isinstance(values, list): values = [values] columns = self.columnize(values[0].keys()) # We need to build a list of parameter place-holders of values that are bound # to the query. Each insert should have the exact same amount of parameter # bindings so we can just go off the first list of values in this array. parameters = self.parameterize(values[0].values()) value = ['(%s)' % parameters] * len(values) parameters = ', '.join(value) return 'INSERT INTO %s (%s) VALUES %s' % (table, columns, parameters)
Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str
entailment
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ sql = [] for column_diff in diff.changed_columns.values(): if self.is_unchanged_binary_column(column_diff): continue old_column_name = column_diff.old_column_name column = column_diff.column if any([column_diff.has_changed('type'), column_diff.has_changed('precision'), column_diff.has_changed('scale'), column_diff.has_changed('fixed')]): query = 'ALTER ' + old_column_name + ' TYPE ' + self.get_sql_type_declaration(column.to_dict()) sql.append('ALTER TABLE ' + diff.name + ' ' + query) if column_diff.has_changed('default') or column_diff.has_changed('type'): if column.get_default() is None: default_clause = ' DROP DEFAULT' else: default_clause = ' SET' + self.get_default_value_declaration_sql(column.to_dict()) query = 'ALTER ' + old_column_name + default_clause sql.append('ALTER TABLE ' + diff.name + ' ' + query) if column_diff.has_changed('notnull'): op = 'DROP' if column.get_notnull(): op = 'SET' query = 'ALTER ' + old_column_name + ' ' + op + ' NOT NULL' sql.append('ALTER TABLE ' + diff.name + ' ' + query) if column_diff.has_changed('autoincrement'): if column.get_autoincrement(): seq_name = self.get_identity_sequence_name(diff.name, old_column_name) sql.append('CREATE SEQUENCE ' + seq_name) sql.append('SELECT setval(\'' + seq_name + '\', ' '(SELECT MAX(' + old_column_name + ') FROM ' + diff.name + '))') query = 'ALTER ' + old_column_name + ' SET DEFAULT nextval(\'' + seq_name + '\')' sql.append('ALTER TABLE ' + diff.name + ' ' + query) else: query = 'ALTER ' + old_column_name + ' DROP DEFAULT' sql.append('ALTER TABLE ' + diff.name + ' ' + query) if column_diff.has_changed('length'): query = 'ALTER ' + old_column_name + ' TYPE ' + self.get_sql_type_declaration(column.to_dict()) sql.append('ALTER TABLE ' + diff.name + ' ' + query) for old_column_name, column in diff.renamed_columns.items(): sql.append('ALTER TABLE ' + diff.name + ' ' 'RENAME COLUMN ' + old_column_name + ' TO ' + column.get_name()) return sql
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
entailment
def _date_based_where(self, type, query, where): """ Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :return: The compiled clause :rtype: str """ value = str(where['value']).zfill(2) value = self.parameter(value) return 'strftime(\'%s\', %s) %s %s'\ % (type, self.wrap(where['column']), where['operator'], value)
Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :return: The compiled clause :rtype: str
entailment
def compile_select(self, query): """ Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ sql = super(MySqlQueryGrammar, self).compile_select(query) if query.unions: sql = '(%s) %s' % (sql, self._compile_unions(query)) return sql
Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str
entailment
def _compile_lock(self, query, value): """ Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str """ if isinstance(value, basestring): return value if value is True: return 'FOR UPDATE' elif value is False: return 'LOCK IN SHARE MODE'
Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str
entailment
def compile_update(self, query, values): """ Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str """ sql = super(MySqlQueryGrammar, self).compile_update(query, values) if query.orders: sql += ' %s' % self._compile_orders(query, query.orders) if query.limit_: sql += ' %s' % self._compile_limit(query, query.limit_) return sql.rstrip()
Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str
entailment
def collapse(self): """ Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection """ results = [] if isinstance(self._items, dict): items = self._items.values() for values in items: if isinstance(values, Collection): values = values.all() results += values return Collection(results)
Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection
entailment
def contains(self, key, value=None): """ Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool """ if value is not None: if isinstance(self._items, list): return key in self._items and self._items[self._items.index(key)] == value return self._items.get(key) == value return key in self._items
Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool
entailment
def lists(self, value, key=None): """ Get a list with the values of a given key :rtype: list """ results = map(lambda x: x[value], self._items) return list(results)
Get a list with the values of a given key :rtype: list
entailment
def map(self, callback): """ Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection """ if isinstance(self._items, dict): return Collection(list(map(callback, self._items.values()))) return Collection(list(map(callback, self._items)))
Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection
entailment
def unique(self): """ Return only unique items from the collection list. :rtype: Collection """ seen = set() seen_add = seen.add return Collection([x for x in self._items if not (x in seen or seen_add(x))])
Return only unique items from the collection list. :rtype: Collection
entailment
def load(self, *relations): """ Load a set of relationships onto the collection. """ if len(self._items) > 0: query = self.first().new_query().with_(*relations) self._items = query.eager_load_relations(self._items) return self
Load a set of relationships onto the collection.
entailment
def compile_foreign(self, blueprint, command, _): """ Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str """ table = self.wrap_table(blueprint) on = self.wrap_table(command.on) columns = self.columnize(command.columns) on_columns = self.columnize(command.references if isinstance(command.references, list) else [command.references]) sql = 'ALTER TABLE %s ADD CONSTRAINT %s ' % (table, command.index) sql += 'FOREIGN KEY (%s) REFERENCES %s (%s)' % (columns, on, on_columns) if command.get('on_delete'): sql += ' ON DELETE %s' % command.on_delete if command.get('on_update'): sql += ' ON UPDATE %s' % command.on_update return sql
Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str
entailment
def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list """ columns = [] for column in blueprint.get_added_columns(): sql = self.wrap(column) + ' ' + self._get_type(column) columns.append(self._add_modifiers(sql, blueprint, column)) return columns
Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list
entailment
def _add_modifiers(self, sql, blueprint, column): """ Add the column modifiers to the deifinition """ for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += getattr(self, method)(blueprint, column) return sql
Add the column modifiers to the deifinition
entailment
def _clean_pivot_attributes(self, model): """ Get the pivot attributes from a model. :type model: eloquent.Model """ values = {} delete_keys = [] for key, value in model.get_attributes().items(): if key.find('pivot_') == 0: values[key[6:]] = value delete_keys.append(key) for key in delete_keys: delattr(model, key) return values
Get the pivot attributes from a model. :type model: eloquent.Model
entailment
def get_relation_count_query_for_self_join(self, query, parent): """ Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder """ query.select(QueryExpression('COUNT(*)')) table_prefix = self._query.get_query().get_connection().get_table_prefix() hash_ = self.get_relation_count_hash() query.from_('%s AS %s%s' % (self._table, table_prefix, hash_)) key = self.wrap(self.get_qualified_parent_key_name()) return query.where('%s.%s' % (hash_, self._foreign_key), '=', QueryExpression(key))
Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder
entailment
def _get_select_columns(self, columns=None): """ Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list """ if columns == ['*'] or columns is None: columns = ['%s.*' % self._related.get_table()] return columns + self._get_aliased_pivot_columns()
Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list
entailment
def _get_aliased_pivot_columns(self): """ Get the pivot columns for the relation. :rtype: list """ defaults = [self._foreign_key, self._other_key] columns = [] for column in defaults + self._pivot_columns: value = '%s.%s AS pivot_%s' % (self._table, column, column) if value not in columns: columns.append('%s.%s AS pivot_%s' % (self._table, column, column)) return columns
Get the pivot columns for the relation. :rtype: list
entailment
def _set_join(self, query=None): """ Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany """ if not query: query = self._query base_table = self._related.get_table() key = '%s.%s' % (base_table, self._related.get_key_name()) query.join(self._table, key, '=', self.get_other_key()) return self
Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany
entailment
def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str """ dictionary = self._build_dictionary(results) for model in models: key = model.get_key() if key in dictionary: collection = self._related.new_collection(dictionary[key]) model.set_relation(relation, collection) return models
Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str
entailment
def save(self, model, joining=None, touch=True): """ Save a new model and attach it to the parent model. :type model: eloquent.Model :type joining: dict :type touch: bool :rtype: eloquent.Model """ if joining is None: joining = {} model.save({'touch': False}) self.attach(model.get_key(), joining, touch) return model
Save a new model and attach it to the parent model. :type model: eloquent.Model :type joining: dict :type touch: bool :rtype: eloquent.Model
entailment
def _attach_new(self, records, current, touch=True): """ Attach all of the IDs that aren't in the current dict. """ changes = { 'attached': [], 'updated': [] } for id, attributes in records.items(): if id not in current: self.attach(id, attributes, touch) changes['attached'].append(id) elif len(attributes) > 0 and self.update_existing_pivot(id, attributes, touch): changes['updated'].append(id) return changes
Attach all of the IDs that aren't in the current dict.
entailment
def update_existing_pivot(self, id, attributes, touch=True): """ Update an existing pivot record on the table. """ if self.updated_at() in self._pivot_columns: attributes = self.set_timestamps_on_attach(attributes, True) updated = self._new_picot_statement_for_id(id).update(attributes) if touch: self.touch_if_touching() return updated
Update an existing pivot record on the table.
entailment
def query(self): """ Begin a fluent query :return: A QueryBuilder instance :rtype: QueryBuilder """ query = QueryBuilder(self, self._query_grammar, self._post_processor) return query
Begin a fluent query :return: A QueryBuilder instance :rtype: QueryBuilder
entailment
def force_delete(self): """ Force a hard delete on a soft deleted model. """ self._force_deleting = True self.delete() self._force_deleting = False
Force a hard delete on a soft deleted model.
entailment
def _do_perform_delete_on_model(self): """ Perform the actual delete query on this model instance. """ if self._force_deleting: return self.with_trashed().where(self.get_key_name(), self.get_key()).force_delete() return self._run_soft_delete()
Perform the actual delete query on this model instance.
entailment
def restore(self): """ Restore a soft-deleted model instance. """ setattr(self, self.get_deleted_at_column(), None) self.set_exists(True) result = self.save() return result
Restore a soft-deleted model instance.
entailment
def join(self, table, one=None, operator=None, two=None, type='inner', where=False): """ Add a join clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :type operator: str :param two: The second column of the join condition :type two: str :param type: The join type :type type: str :param where: Whether to use a "where" rather than a "on" :type where: bool :return: The current QueryBuilder instance :rtype: QueryBuilder """ if isinstance(table, JoinClause): self.joins.append(table) else: if one is None: raise ArgumentError('Missing "one" argument') join = JoinClause(table, type) self.joins.append(join.on( one, operator, two, 'and', where )) return self
Add a join clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :type operator: str :param two: The second column of the join condition :type two: str :param type: The join type :type type: str :param where: Whether to use a "where" rather than a "on" :type where: bool :return: The current QueryBuilder instance :rtype: QueryBuilder
entailment
def join_where(self, table, one, operator, two, type='inner'): """ Add a "join where" clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :type operator: str :param two: The second column of the join condition :type two: str :param type: The join type :type type: str :return: The current QueryBuilder instance :rtype: QueryBuilder """ return self.join(table, one, operator, two, type, True)
Add a "join where" clause to the query :param table: The table to join with, can also be a JoinClause instance :type table: str or JoinClause :param one: The first column of the join condition :type one: str :param operator: The operator of the join condition :type operator: str :param two: The second column of the join condition :type two: str :param type: The join type :type type: str :return: The current QueryBuilder instance :rtype: QueryBuilder
entailment
def _where_in_sub(self, column, query, boolean, negate=False): """ Add a where in with a sub select to the query :param column: The column :type column: str :param query: A QueryBuilder instance :type query: QueryBuilder :param boolean: The boolean operator :type boolean: str :param negate: Whether it is a not where in :param negate: bool :return: The current QueryBuilder instance :rtype: QueryBuilder """ if negate: type = 'not_in_sub' else: type = 'in_sub' self.wheres.append({ 'type': type, 'column': column, 'query': query, 'boolean': boolean }) self.merge_bindings(query) return self
Add a where in with a sub select to the query :param column: The column :type column: str :param query: A QueryBuilder instance :type query: QueryBuilder :param boolean: The boolean operator :type boolean: str :param negate: Whether it is a not where in :param negate: bool :return: The current QueryBuilder instance :rtype: QueryBuilder
entailment
def or_having(self, column, operator=None, value=None): """ Add a "having" clause to the query :param column: The column :type column: str :param operator: The having clause operator :type operator: str :param value: The having clause value :type value: mixed :return: The current QueryBuilder instance :rtype: QueryBuilder """ return self.having(column, operator, value, 'or')
Add a "having" clause to the query :param column: The column :type column: str :param operator: The having clause operator :type operator: str :param value: The having clause value :type value: mixed :return: The current QueryBuilder instance :rtype: QueryBuilder
entailment
def union(self, query, all=False): """ Add a union statement to the query :param query: A QueryBuilder instance :type query: QueryBuilder :param all: Whether it is a "union all" statement :type all: bool :return: The query :rtype: QueryBuilder """ self.unions.append({ 'query': query, 'all': all }) return self.merge_bindings(query)
Add a union statement to the query :param query: A QueryBuilder instance :type query: QueryBuilder :param all: Whether it is a "union all" statement :type all: bool :return: The query :rtype: QueryBuilder
entailment
def find(self, id, columns=None): """ Execute a query for a single record by id :param id: The id of the record to retrieve :type id: mixed :param columns: The columns of the record to retrive :type columns: list :return: mixed :rtype: mixed """ if not columns: columns = ['*'] return self.where('id', '=', id).first(1, columns)
Execute a query for a single record by id :param id: The id of the record to retrieve :type id: mixed :param columns: The columns of the record to retrive :type columns: list :return: mixed :rtype: mixed
entailment
def first(self, limit=1, columns=None): """ Execute the query and get the first results :param limit: The number of results to get :type limit: int :param columns: The columns to get :type columns: list :return: The result :rtype: mixed """ if not columns: columns = ['*'] results = self.take(limit).get(columns) if len(results) > 0: return results[0] return
Execute the query and get the first results :param limit: The number of results to get :type limit: int :param columns: The columns to get :type columns: list :return: The result :rtype: mixed
entailment
def get_fresh(self, columns=None): """ Execute the query as a fresh "select" statement :param columns: The columns to get :type columns: list :return: The result :rtype: list """ if not columns: columns = ['*'] if not self.columns: self.columns = columns return self._processor.process_select(self, self._run_select())
Execute the query as a fresh "select" statement :param columns: The columns to get :type columns: list :return: The result :rtype: list
entailment
def _get_list_select(self, column, key=None): """ Get the columns that should be used in a list :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: list """ if key is None: elements = [column] else: elements = [column, key] select = [] for elem in elements: dot = elem.find('.') if dot >= 0: select.append(column[dot + 1:]) else: select.append(elem) return select
Get the columns that should be used in a list :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: list
entailment
def increment(self, column, amount=1, extras=None): """ Increment a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int """ wrapped = self._grammar.wrap(column) if extras is None: extras = {} columns = { column: self.raw('%s + %s' % (wrapped, amount)) } columns.update(extras) return self.update(**columns)
Increment a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int
entailment
def delete(self, id=None): """ Delete a record from the database :param id: The id of the row to delete :type id: mixed :return: The number of rows deleted :rtype: int """ if id is not None: self.where('id', '=', id) sql = self._grammar.compile_delete(self) return self._connection.delete(sql, self.get_bindings())
Delete a record from the database :param id: The id of the row to delete :type id: mixed :return: The number of rows deleted :rtype: int
entailment
def merge_wheres(self, wheres, bindings): """ Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None """ self.wheres = self.wheres + wheres self._bindings['where'] = self._bindings['where'] + bindings
Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None
entailment
def execute(self, i, o): """ Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output """ super(MigrateMakeCommand, self).execute(i, o) creator = MigrationCreator() name = i.get_argument('name') table = i.get_option('table') create = bool(i.get_option('create')) if not table and create is not False: table = create path = i.get_option('path') if path is None: path = self._get_migration_path() file_ = self._write_migration(creator, name, table, create, path) o.writeln('<info>Create migration: <comment>%s</comment></info>' % file_)
Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output
entailment
def remove(self, builder, model): """ Remove the scope from a given query builder. :param builder: The query builder :type builder: eloquent.orm.builder.Builder :param model: The model :type model: eloquent.orm.Model """ column = model.get_qualified_deleted_at_column() query = builder.get_query() wheres = [] for where in query.wheres: # If the where clause is a soft delete date constraint, # we will remove it from the query and reset the keys # on the wheres. This allows the developer to include # deleted model in a relationship result set that is lazy loaded. if not self._is_soft_delete_constraint(where, column): wheres.append(where) query.wheres = wheres
Remove the scope from a given query builder. :param builder: The query builder :type builder: eloquent.orm.builder.Builder :param model: The model :type model: eloquent.orm.Model
entailment
def extend(self, builder): """ Extend the query builder with the needed functions. :param builder: The query builder :type builder: eloquent.orm.builder.Builder """ for extension in self._extensions: getattr(self, '_add_%s' % extension)(builder) builder.on_delete(self._on_delete)
Extend the query builder with the needed functions. :param builder: The query builder :type builder: eloquent.orm.builder.Builder
entailment
def _only_trashed(self, builder): """ The only-trashed extension. :param builder: The query builder :type builder: eloquent.orm.builder.Builder """ model = builder.get_model() self.remove(builder, model) builder.get_query().where_not_null(model.get_qualified_deleted_at_column())
The only-trashed extension. :param builder: The query builder :type builder: eloquent.orm.builder.Builder
entailment
def _add_fluent_indexes(self): """ Add the index commands fluently specified on columns: """ for column in self._columns: for index in ['primary', 'unique', 'index']: column_index = column.get(index) if column_index is True: getattr(self, index)(column.name) break elif column_index: getattr(self, index)(column.name, column_index) break
Add the index commands fluently specified on columns:
entailment
def big_integer(self, column, auto_increment=False, unsigned=False): """ Create a new big integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent """ return self._add_column('big_integer', column, auto_increment=auto_increment, unsigned=unsigned)
Create a new big integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent
entailment
def medium_integer(self, column, auto_increment=False, unsigned=False): """ Create a new medium integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent """ return self._add_column('medium_integer', column, auto_increment=auto_increment, unsigned=unsigned)
Create a new medium integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent
entailment
def tiny_integer(self, column, auto_increment=False, unsigned=False): """ Create a new tiny integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent """ return self._add_column('tiny_integer', column, auto_increment=auto_increment, unsigned=unsigned)
Create a new tiny integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent
entailment
def _add_column(self, type, name, **parameters): """ Add a new column to the blueprint. :param type: The column type :type type: str :param name: The column name :type name: str :param parameters: The column parameters :type parameters: dict :rtype: Fluent """ parameters.update({ 'type': type, 'name': name }) column = Fluent(**parameters) self._columns.append(column) return column
Add a new column to the blueprint. :param type: The column type :type type: str :param name: The column name :type name: str :param parameters: The column parameters :type parameters: dict :rtype: Fluent
entailment
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ #sql = self._get_simple_alter_table_sql(diff) from_table = diff.from_table if not isinstance(from_table, Table): raise Exception('SQLite platform requires for the alter table the table diff ' 'referencing the original table') table = from_table.clone() columns = {} old_column_names = {} new_column_names = {} column_sql = [] for column_name, column in table.get_columns().items(): column_name = column_name.lower() columns[column_name] = column old_column_names[column_name] = column.get_name() new_column_names[column_name] = column.get_name() for column_name, column in diff.removed_columns.items(): column_name = column_name.lower() if column_name in columns: del columns[column_name] del old_column_names[column_name] del new_column_names[column_name] for old_column_name, column in diff.renamed_columns.items(): old_column_name = old_column_name.lower() if old_column_name in columns: del columns[old_column_name] columns[column.get_name().lower()] = column if old_column_name in new_column_names: new_column_names[old_column_name] = column.get_name() for old_column_name, column_diff in diff.changed_columns.items(): if old_column_name in columns: del columns[old_column_name] columns[column_diff.column.get_name().lower()] = column_diff.column if old_column_name in new_column_names: new_column_names[old_column_name] = column_diff.column.get_name() for column_name, column in diff.added_columns.items(): columns[column_name.lower()] = column sql = [] table_sql = [] data_table = Table('__temp__' + table.get_name()) new_table = Table(table.get_name(), columns, self.get_primary_index_in_altered_table(diff), self.get_foreign_keys_in_altered_table(diff)) new_table.add_option('alter', True) sql = self.get_pre_alter_table_index_foreign_key_sql(diff) sql.append('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s' % (data_table.get_name(), ', '.join(old_column_names.values()), table.get_name())) sql.append(self.get_drop_table_sql(from_table)) sql += self.get_create_table_sql(new_table) sql.append('INSERT INTO %s (%s) SELECT %s FROM %s' % (new_table.get_name(), ', '.join(new_column_names.values()), ', '.join(old_column_names.values()), data_table.get_name())) sql.append(self.get_drop_table_sql(data_table)) sql += self.get_post_alter_table_index_foreign_key_sql(diff) return sql
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
entailment
def get_foreign_keys_in_altered_table(self, diff): """ :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ foreign_keys = diff.from_table.get_foreign_keys() column_names = self.get_column_names_in_altered_table(diff) for key, constraint in foreign_keys.items(): changed = False local_columns = [] for column_name in constraint.get_local_columns(): normalized_column_name = column_name.lower() if normalized_column_name not in column_names: del foreign_keys[key] break else: local_columns.append(column_names[normalized_column_name]) if column_name != column_names[normalized_column_name]: changed = True if changed: pass return foreign_keys
:param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
entailment
def get_relation_count_query(self, query, parent): """ Add the constraints for a relationship count query. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: Builder """ query.select(QueryExpression('COUNT(*)')) other_key = self.wrap('%s.%s' % (query.get_model().get_table(), self._other_key)) return query.where(self.get_qualified_foreign_key(), '=', QueryExpression(other_key))
Add the constraints for a relationship count query. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: Builder
entailment
def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str """ foreign = self._foreign_key other = self._other_key dictionary = {} for result in results: dictionary[result.get_attribute(other)] = result for model in models: value = model.get_attribute(foreign) if value in dictionary: model.set_relation(relation, dictionary[value]) return models
Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str
entailment
def associate(self, model): """ Associate the model instance to the given parent. :type model: eloquent.Model :rtype: eloquent.Model """ self._parent.set_attribute(self._foreign_key, model.get_attribute(self._other_key)) return self._parent.set_relation(self._relation, model)
Associate the model instance to the given parent. :type model: eloquent.Model :rtype: eloquent.Model
entailment
def dissociate(self): """ Dissociate previously associated model from the given parent. :rtype: eloquent.Model """ self._parent.set_attribute(self._foreign_key, None) return self._parent.set_relation(self._relation, None)
Dissociate previously associated model from the given parent. :rtype: eloquent.Model
entailment
def execute(self, i, o): """ Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output """ super(StatusCommand, self).execute(i, o) database = i.get_option('database') repository = DatabaseMigrationRepository(self._resolver, 'migrations') migrator = Migrator(repository, self._resolver) if not migrator.repository_exists(): return o.writeln('<error>No migrations found</error>') self._prepare_database(migrator, database, i, o) path = i.get_option('path') if path is None: path = self._get_migration_path() ran = migrator.get_repository().get_ran() migrations = [] for migration in migrator._get_migration_files(path): if migration in ran: migrations.append(['<fg=cyan>%s</>' % migration, '<info>Yes</info>']) else: migrations.append(['<fg=cyan>%s</>' % migration, '<fg=red>No</>']) if migrations: table = self.get_helper('table') table.set_headers(['Migration', 'Ran?']) table.set_rows(migrations) table.render(o) else: return o.writeln('<error>No migrations found</error>') for note in migrator.get_notes(): o.writeln(note)
Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output
entailment
def compile_rename_column(self, blueprint, command, connection): """ Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: eloquent.connections.Connection :rtype: list """ # The code is a little complex. It will propably change # if we support complete diffs in dbal sql = [] schema = connection.get_schema_manager() table = self.get_table_prefix() + blueprint.get_table() column = connection.get_column(table, command.from_) columns = schema.list_table_columns(table) indexes = schema.list_table_indexes(table) foreign_keys = schema.list_table_foreign_keys(table) diff = self._get_renamed_diff(blueprint, command, column, schema) renamed_columns = diff.renamed_columns old_column_names = list(map(lambda x: x.get_name(), columns)) # We build the new column names new_column_names = [] for column_name in old_column_names: if column_name in renamed_columns: new_column_names.append(renamed_columns[column_name].get_name()) else: new_column_names.append(column_name) # We create a temporary table and insert the data into it temp_table = '__temp__' + self.get_table_prefix() + blueprint.get_table() sql.append('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s' % (temp_table, self.columnize(old_column_names), table)) # We drop the current table sql += Blueprint(table).drop().to_sql(None, self) # Building the list a new columns new_columns = [] for column in columns: for column_name, changed_column in renamed_columns.items(): if column_name == column.get_name(): new_columns.append(changed_column) # Here we will try to rebuild a new blueprint to create a new table # with the original name new_blueprint = Blueprint(table) new_blueprint.create() primary = [] for column in columns: # Mapping the database type to the blueprint type type = schema.get_database_platform().TYPE_MAPPING[column.get_type().lower()] # If the column is a primary, we will add it to the blueprint later if column.get_platform_option('pk'): primary.append(column.get_name()) # If the column is not one that's been renamed we reinsert it into the blueprint if column.get_name() not in renamed_columns.keys(): col = getattr(new_blueprint, type)(column.get_name()) # If the column is nullable, we flag it if not column.get_notnull(): col.nullable() # If the column has a default value, we add it if column.get_default() is not None: col.default(QueryExpression(column.get_default())) # Inserting the renamed columns into the blueprint for column in new_columns: type = schema.get_database_platform().TYPE_MAPPING[column.get_type().lower()] col = getattr(new_blueprint, type)(column.get_name()) if not column.get_notnull(): col.nullable() if column.get_default() is not None: col.default(QueryExpression(column.get_default())) # We add the primary keys if primary: new_blueprint.primary(primary) # We rebuild the indexes for index in indexes: index_columns = index['columns'] new_index_columns = [] index_name = index['name'] for column_name in index_columns: if column_name in renamed_columns: new_index_columns.append(renamed_columns[column_name].get_name()) else: new_index_columns.append(column_name) if index_columns != new_index_columns: index_name = None if index['unique']: new_blueprint.unique(new_index_columns, index_name) else: new_blueprint.index(index['columns'], index_name) for foreign_key in foreign_keys: fkey_from = foreign_key['from'] if fkey_from in renamed_columns: fkey_from = renamed_columns[fkey_from].get_name() new_blueprint.foreign(fkey_from)\ .references(foreign_key['to'])\ .on(foreign_key['table'])\ .on_delete(foreign_key['on_delete'])\ .on_update(foreign_key['on_update']) # We create the table sql += new_blueprint.to_sql(None, self) # We reinsert the data into the new table sql.append('INSERT INTO %s (%s) SELECT %s FROM %s' % (self.wrap_table(table), ', '.join(new_column_names), self.columnize(old_column_names), self.wrap_table(temp_table) )) # Finally we drop the temporary table sql += Blueprint(temp_table).drop().to_sql(None, self) return sql
Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: eloquent.connections.Connection :rtype: list
entailment
def compile_change(self, blueprint, command, connection): """ Compile a change column command into a series of SQL statement. :param blueprint: The blueprint :type blueprint: eloquent.schema.Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: eloquent.connections.Connection :rtype: list """ sql = [] schema = connection.get_schema_manager() table = self.get_table_prefix() + blueprint.get_table() columns = schema.list_table_columns(table) indexes = schema.list_table_indexes(table) foreign_keys = schema.list_table_foreign_keys(table) diff = self._get_changed_diff(blueprint, schema) blueprint_changed_columns = blueprint.get_changed_columns() changed_columns = diff.changed_columns temp_table = '__temp__' + self.get_table_prefix() + blueprint.get_table() sql.append('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s' % (temp_table, self.columnize(list(map(lambda x: x.get_name(), columns))), table)) sql += Blueprint(table).drop().to_sql(None, self) new_columns = [] for column in columns: for column_name, changed_column in changed_columns.items(): if column_name == column.get_name(): for blueprint_column in blueprint_changed_columns: if blueprint_column.name == column_name: new_columns.append(blueprint_column) break break new_blueprint = Blueprint(table) new_blueprint.create() primary = [] new_column_names = [] for column in columns: type = schema.get_database_platform().TYPE_MAPPING[column.get_type().lower()] if column.get_platform_option('pk'): primary.append(column.get_name()) if column.get_name() not in changed_columns: col = getattr(new_blueprint, type)(column.get_name()) if not column.get_notnull(): col.nullable() new_column_names.append(column.get_name()) for column in new_columns: column.change = False new_blueprint._add_column(**column.get_attributes()) new_column_names.append(column.name) if primary: new_blueprint.primary(primary) for index in indexes: if index['unique']: new_blueprint.unique(index['columns'], index['name']) else: new_blueprint.index(index['columns'], index['name']) for foreign_key in foreign_keys: new_blueprint.foreign(foreign_key['from'])\ .references(foreign_key['to'])\ .on(foreign_key['table'])\ .on_delete(foreign_key['on_delete'])\ .on_update(foreign_key['on_update']) sql += new_blueprint.to_sql(None, self) sql.append('INSERT INTO %s (%s) SELECT %s FROM %s' % (self.wrap_table(table), ', '.join(sorted(new_column_names)), self.columnize(sorted(list(map(lambda x: x.get_name(), columns)))), self.wrap_table(temp_table) )) sql += Blueprint(temp_table).drop().to_sql(None, self) return sql
Compile a change column command into a series of SQL statement. :param blueprint: The blueprint :type blueprint: eloquent.schema.Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: eloquent.connections.Connection :rtype: list
entailment
def compile_create(self, blueprint, command, _): """ Compile a create table command. """ columns = ', '.join(self._get_columns(blueprint)) sql = 'CREATE TABLE %s (%s' % (self.wrap_table(blueprint), columns) sql += self._add_foreign_keys(blueprint) sql += self._add_primary_keys(blueprint) return sql + ')'
Compile a create table command.
entailment
def match_one(self, models, results, relation): """ Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :rtype: list """ return self._match_one_or_many(models, results, relation, 'one')
Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :rtype: list
entailment
def match_many(self, models, results, relation): """ Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :rtype: list """ return self._match_one_or_many(models, results, relation, 'many')
Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :rtype: list
entailment
def _match_one_or_many(self, models, results, relation, type): """ Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :param type: The match type :type type: str :rtype: list """ dictionary = self._build_dictionary(results) for model in models: key = model.get_attribute(self._local_key) if key in dictionary: value = self._get_relation_value(dictionary, key, type) model.set_relation(relation, value) return models
Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :param type: The match type :type type: str :rtype: list
entailment
def _get_relation_value(self, dictionary, key, type): """ Get the value of the relationship by one or many type. :type dictionary: dict :type key: str :type type: str """ value = dictionary[key] if type == 'one': return value[0] return self._related.new_collection(value)
Get the value of the relationship by one or many type. :type dictionary: dict :type key: str :type type: str
entailment
def first_or_new(self, _attributes=None, **attributes): """ Get the first related model record matching the attributes or instantiate it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attributes.update(_attributes) instance = self.where(attributes).first() if instance is None: instance = self._related.new_instance() instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_key()) return instance
Get the first related model record matching the attributes or instantiate it. :param attributes: The attributes :type attributes: dict :rtype: Model
entailment
def first_or_create(self, _attributes=None, **attributes): """ Get the first related record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attributes.update(_attributes) instance = self.where(attributes).first() if instance is None: instance = self.create(**attributes) return instance
Get the first related record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model
entailment
def execute(self, i, o): """ Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output """ super(ResetCommand, self).execute(i, o) dialog = self.get_helper('dialog') confirm = dialog.ask_confirmation( o, '<question>Are you sure you want to reset all of the migrations?</question> ', False ) if not confirm: return database = i.get_option('database') repository = DatabaseMigrationRepository(self._resolver, 'migrations') migrator = Migrator(repository, self._resolver) self._prepare_database(migrator, database, i, o) pretend = bool(i.get_option('pretend')) path = i.get_option('path') if path is None: path = self._get_migration_path() while True: count = migrator.rollback(path, pretend) for note in migrator.get_notes(): o.writeln(note) if count == 0: break
Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output
entailment
def get_relation_count_query(self, query, parent): """ Add the constraints for a relationship count query. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder """ query = super(MorphToMany, self).get_relation_count_query(query, parent) return query.where('%s.%s' % (self._table, self._morph_type), self._morph_class)
Add the constraints for a relationship count query. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder
entailment
def add_eager_constraints(self, models): """ Set the constraints for an eager load of the relation. :type models: list """ super(MorphToMany, self).add_eager_constraints(models) self._query.where('%s.%s' % (self._table, self._morph_type), self._morph_class)
Set the constraints for an eager load of the relation. :type models: list
entailment
def _create_attach_record(self, id, timed): """ Create a new pivot attachement record. """ record = super(MorphToMany, self)._create_attach_record(id, timed) record[self._morph_type] = self._morph_class return record
Create a new pivot attachement record.
entailment
def _new_pivot_query(self): """ Create a new query builder for the pivot table. :rtype: eloquent.orm.Builder """ query = super(MorphToMany, self)._new_pivot_query() return query.where(self._morph_type, self._morph_class)
Create a new query builder for the pivot table. :rtype: eloquent.orm.Builder
entailment
def new_pivot(self, attributes=None, exists=False): """ Create a new pivot model instance. """ from .morph_pivot import MorphPivot pivot = MorphPivot(self._parent, attributes, self._table, exists) pivot.set_pivot_keys(self._foreign_key, self._other_key)\ .set_morph_type(self._morph_type)\ .set_morph_class(self._morph_class) return pivot
Create a new pivot model instance.
entailment
def execute(self, i, o): """ Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output """ super(InstallCommand, self).execute(i, o) database = i.get_option('database') repository = DatabaseMigrationRepository(self._resolver, 'migrations') repository.set_source(database) repository.create_repository() o.writeln('<info>Migration table created successfully</info>')
Executes the command. :type i: cleo.inputs.input.Input :type o: cleo.outputs.output.Output
entailment
def process_insert_get_id(self, query, sql, values, sequence=None): """ Process an "insert get ID" query. :param query: A QueryBuilder instance :type query: QueryBuilder :param sql: The sql query to execute :type sql: str :param values: The value bindings :type values: list :param sequence: The ids sequence :type sequence: str :return: The inserted row id :rtype: int """ if not query.get_connection().transaction_level(): with query.get_connection().transaction(): query.get_connection().insert(sql, values) cursor = query.get_connection().get_cursor() if hasattr(cursor, 'lastrowid'): id = cursor.lastrowid else: id = query.get_connection().statement('SELECT LAST_INSERT_ID()') else: query.get_connection().insert(sql, values) cursor = query.get_connection().get_cursor() if hasattr(cursor, 'lastrowid'): id = cursor.lastrowid else: id = query.get_connection().statement('SELECT LAST_INSERT_ID()') if isinstance(id, int): return id if str(id).isdigit(): return int(id) return id
Process an "insert get ID" query. :param query: A QueryBuilder instance :type query: QueryBuilder :param sql: The sql query to execute :type sql: str :param values: The value bindings :type values: list :param sequence: The ids sequence :type sequence: str :return: The inserted row id :rtype: int
entailment
def chunk(self, count): """ Chunk the results of the query :param count: The chunk size :type count: int :return: The current chunk :rtype: list """ page = 1 results = self.for_page(page, count).get() while results: yield results page += 1 results = self.for_page(page, count).get()
Chunk the results of the query :param count: The chunk size :type count: int :return: The current chunk :rtype: list
entailment
def lists(self, column, key=None): """ Get a list with the values of a given column :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: list or dict """ results = self._query.lists(column, key) if self._model.has_get_mutator(column): if isinstance(results, dict): for key, value in results.items(): fill = {column: value} results[key] = self._model.new_from_builder(fill).column else: for i, value in enumerate(results): fill = {column: value} results[i] = self._model.new_from_builder(fill).column return results
Get a list with the values of a given column :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: list or dict
entailment
def increment(self, column, amount=1, extras=None): """ Increment a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int """ extras = self._add_updated_at_column(extras) return self._query.increment(column, amount, extras)
Increment a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int
entailment
def decrement(self, column, amount=1, extras=None): """ Decrement a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int """ extras = self._add_updated_at_column(extras) return self._query.decrement(column, amount, extras)
Decrement a column's value by a given amount :param column: The column to increment :type column: str :param amount: The amount by which to increment :type amount: int :param extras: Extra columns :type extras: dict :return: The number of rows affected :rtype: int
entailment
def get_models(self, columns=None): """ Get the hydrated models without eager loading. :param columns: The columns to get :type columns: list :return: A list of models :rtype: list """ results = self._query.get(columns) connection = self._model.get_connection_name() return self._model.hydrate(results, connection).all()
Get the hydrated models without eager loading. :param columns: The columns to get :type columns: list :return: A list of models :rtype: list
entailment
def eager_load_relations(self, models): """ Eager load the relationship of the models. :param models: :type models: list :return: The models :rtype: list """ for name, constraints in self._eager_load.items(): if name.find('.') == -1: models = self._load_relation(models, name, constraints) return models
Eager load the relationship of the models. :param models: :type models: list :return: The models :rtype: list
entailment
def _load_relation(self, models, name, constraints): """ Eagerly load the relationship on a set of models. :rtype: list """ relation = self.get_relation(name) relation.add_eager_constraints(models) if callable(constraints): constraints(relation) else: relation.merge_query(constraints) models = relation.init_relation(models, name) results = relation.get_eager() return relation.match(models, results, name)
Eagerly load the relationship on a set of models. :rtype: list
entailment
def _has_nested(self, relations, operator='>=', count=1, boolean='and', extra=None): """ Add nested relationship count conditions to the query. :param relations: nested relations :type relations: str :param operator: The operator :type operator: str :param count: The count :type count: int :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :rtype: Builder """ relations = relations.split('.') def closure(q): if len(relations) > 1: q.where_has(relations.pop(0), closure) else: q.has(relations.pop(0), operator, count, boolean, extra) return self.where_has(relations.pop(0), closure)
Add nested relationship count conditions to the query. :param relations: nested relations :type relations: str :param operator: The operator :type operator: str :param count: The count :type count: int :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :rtype: Builder
entailment
def doesnt_have(self, relation, boolean='and', extra=None): """ Add a relationship count to the query. :param relation: The relation to count :type relation: str :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :rtype: Builder """ return self.has(relation, '<', 1, boolean, extra)
Add a relationship count to the query. :param relation: The relation to count :type relation: str :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :rtype: Builder
entailment
def where_has(self, relation, extra, operator='>=', count=1): """ Add a relationship count condition to the query with where clauses. :param relation: The relation to count :type relation: str :param extra: The extra query :type extra: Builder or callable :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder """ return self.has(relation, operator, count, 'and', extra)
Add a relationship count condition to the query with where clauses. :param relation: The relation to count :type relation: str :param extra: The extra query :type extra: Builder or callable :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder
entailment
def or_has(self, relation, operator='>=', count=1): """ Add a relationship count condition to the query with an "or". :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder """ return self.has(relation, operator, count, 'or')
Add a relationship count condition to the query with an "or". :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder
entailment
def or_where_has(self, relation, extra, operator='>=', count=1): """ Add a relationship count condition to the query with where clauses and an "or". :param relation: The relation to count :type relation: str :param extra: The extra query :type extra: Builder or callable :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder """ return self.has(relation, operator, count, 'or', extra)
Add a relationship count condition to the query with where clauses and an "or". :param relation: The relation to count :type relation: str :param extra: The extra query :type extra: Builder or callable :param operator: The operator :type operator: str :param count: The count :type count: int :rtype: Builder
entailment
def _merge_wheres_to_has(self, has_query, relation): """ Merge the "wheres" from the relation query to a has query. :param has_query: The has query :type has_query: Builder :param relation: The relation to count :type relation: eloquent.orm.relations.Relation """ relation_query = relation.get_base_query() has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings()) self._query.merge_bindings(has_query.get_query())
Merge the "wheres" from the relation query to a has query. :param has_query: The has query :type has_query: Builder :param relation: The relation to count :type relation: eloquent.orm.relations.Relation
entailment
def _get_has_relation_query(self, relation): """ Get the "has" relation base query :type relation: str :rtype: Builder """ from .relations import Relation return Relation.no_constraints( lambda: getattr(self.get_model(), relation)() )
Get the "has" relation base query :type relation: str :rtype: Builder
entailment
def with_(self, *relations): """ Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder """ if not relations: return self eagers = self._parse_relations(list(relations)) self._eager_load.update(eagers) return self
Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder
entailment
def _parse_relations(self, relations): """ Parse a list of relations into individuals. :param relations: The relation to parse :type relations: list :rtype: dict """ results = {} for relation in relations: if isinstance(relation, dict): name = list(relation.keys())[0] constraints = relation[name] else: name = relation constraints = self.__class__(self.get_query().new_query()) results = self._parse_nested(name, results) results[name] = constraints return results
Parse a list of relations into individuals. :param relations: The relation to parse :type relations: list :rtype: dict
entailment
def _parse_nested(self, name, results): """ Parse the nested relationship in a relation. :param name: The name of the relationship :type name: str :type results: dict :rtype: dict """ progress = [] for segment in name.split('.'): progress.append(segment) last = '.'.join(progress) if last not in results: results[last] = self.__class__(self.get_query().new_query()) return results
Parse the nested relationship in a relation. :param name: The name of the relationship :type name: str :type results: dict :rtype: dict
entailment
def _call_scope(self, scope, *args, **kwargs): """ Call the given model scope. :param scope: The scope to call :type scope: str """ result = getattr(self._model, scope)(self, *args, **kwargs) return result or self
Call the given model scope. :param scope: The scope to call :type scope: str
entailment
def _run_up(self, path, migration_file, batch, pretend=False): """ Run "up" a migration instance. :type migration_file: str :type batch: int :type pretend: bool """ migration = self._resolve(path, migration_file) if pretend: return self._pretend_to_run(migration, 'up') migration.up() self._repository.log(migration_file, batch) self._note('<info>✓ Migrated</info> %s' % migration_file)
Run "up" a migration instance. :type migration_file: str :type batch: int :type pretend: bool
entailment
def rollback(self, path, pretend=False): """ Rollback the last migration operation. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: int """ self._notes = [] migrations = self._repository.get_last() if not migrations: self._note('<info>Nothing to rollback.</info>') return len(migrations) for migration in migrations: self._run_down(path, migration, pretend) return len(migrations)
Rollback the last migration operation. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: int
entailment
def _run_down(self, path, migration, pretend=False): """ Run "down" a migration instance. """ migration_file = migration['migration'] instance = self._resolve(path, migration_file) if pretend: return self._pretend_to_run(instance, 'down') instance.down() self._repository.delete(migration) self._note('<info>✓ Rolled back</info> %s' % migration_file)
Run "down" a migration instance.
entailment
def _pretend_to_run(self, migration, method): """ Pretend to run the migration. :param migration: The migration :type migration: eloquent.migrations.migration.Migration :param method: The method to execute :type method: str """ for query in self._get_queries(migration, method): name = migration.__class__.__name__ self._note('<info>%s:</info> <comment>%s</comment>' % (name, query))
Pretend to run the migration. :param migration: The migration :type migration: eloquent.migrations.migration.Migration :param method: The method to execute :type method: str
entailment
def _get_queries(self, migration, method): """ Get all of the queries that would be run for a migration. :param migration: The migration :type migration: eloquent.migrations.migration.Migration :param method: The method to execute :type method: str :rtype: list """ connection = migration.get_connection() db = self.resolve_connection(connection) logger = logging.getLogger('eloquent.connection.queries') level = logger.level logger.setLevel(logging.DEBUG) handler = MigratorHandler() handler.setLevel(logging.DEBUG) logger.addHandler(handler) db.pretend(lambda _: getattr(migration, method)()) logger.removeHandler(handler) logger.setLevel(level) return handler.queries
Get all of the queries that would be run for a migration. :param migration: The migration :type migration: eloquent.migrations.migration.Migration :param method: The method to execute :type method: str :rtype: list
entailment
def _resolve(self, path, migration_file): """ Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration """ variables = {} name = '_'.join(migration_file.split('_')[4:]) migration_file = os.path.join(path, '%s.py' % migration_file) with open(migration_file) as fh: exec(fh.read(), {}, variables) klass = variables[inflection.camelize(name)] instance = klass() instance.set_schema_builder(self.get_repository().get_connection().get_schema_builder()) return instance
Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration
entailment
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ column_sql = [] query_parts = [] if diff.new_name is not False: query_parts.append('RENAME TO %s' % diff.new_name) # Added columns? # Removed columns? for column_diff in diff.changed_columns.values(): column = column_diff.column column_dict = column.to_dict() # Don't propagate default value changes for unsupported column types. if column_diff.has_changed('default') \ and len(column_diff.changed_properties) == 1 \ and (column_dict['type'] == 'text' or column_dict['type'] == 'blob'): continue query_parts.append('CHANGE %s %s' % (column_diff.get_old_column_name(), self.get_column_declaration_sql(column.get_name(), column_dict))) for old_column_name, column in diff.renamed_columns.items(): column_dict = column.to_dict() query_parts.append('CHANGE %s %s' % (self.quote(old_column_name), self.get_column_declaration_sql(self.quote(column.get_name()), column_dict))) sql = [] if len(query_parts) > 0: sql.append('ALTER TABLE %s %s' % (diff.name, ', '.join(query_parts))) return sql
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
entailment
def diff_table(self, table1, table2): """ Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff """ changes = 0 table_differences = TableDiff(table1.get_name()) table_differences.from_table = table1 table1_columns = table1.get_columns() table2_columns = table2.get_columns() # See if all the fields in table1 exist in table2 for column_name, column in table2_columns.items(): if not table1.has_column(column_name): table_differences.added_columns[column_name] = column changes += 1 # See if there are any removed fields in table2 for column_name, column in table1_columns.items(): if not table2.has_column(column_name): table_differences.removed_columns[column_name] = column changes += 1 continue # See if column has changed properties in table2 changed_properties = self.diff_column(column, table2.get_column(column_name)) if changed_properties: column_diff = ColumnDiff(column.get_name(), table2.get_column(column_name), changed_properties) column_diff.from_column = column table_differences.changed_columns[column.get_name()] = column_diff changes += 1 self.detect_column_renamings(table_differences) # table1_indexes = table1.get_indexes() # table2_indexes = table2.get_indexes() # # # See if all the fields in table1 exist in table2 # for index_name, index in table2_indexes.items(): # if (index.is_primary() and table1.has_primary_key()) or table1.has_index(index_name): # continue # # table_differences.added_indexes[index_name] = index # changes += 1 # # # See if there are any removed fields in table2 # for index_name, index in table1_indexes.items(): # if (index.is_primary() and not table2.has_primary_key())\ # or (not index.is_primary() and not table2.has_index(index_name)): # table_differences.removed_indexes[index_name] = index # changes += 1 # continue # # if index.is_primary(): # table2_index = table2.get_primary_key() # else: # table2_index = table2.get_index(index_name) # # if self.diff_index(index, table2_index): # table_differences.changed_indexes[index_name] = index # changes += 1 # # self.detect_index_renamings(table_differences) # # from_fkeys = table1.get_foreign_keys() # to_fkeys = table2.get_foreign_keys() # # for key1, constraint1 in from_fkeys.items(): # for key2, constraint2 in to_fkeys.items(): # if self.diff_foreign_key(constraint1, constraint2) is False: # del from_fkeys[key1] # del to_fkeys[key2] # else: # if constraint1.get_name().lower() == constraint2.get_name().lower(): # table_differences.changed_foreign_keys.append(constraint2) # changes += 1 # del from_fkeys[key1] # del to_fkeys[key2] # # for constraint1 in from_fkeys.values(): # table_differences.removed_foreign_keys.append(constraint1) # changes += 1 # # for constraint2 in to_fkeys.values(): # table_differences.added_foreign_keys.append(constraint2) # changes += 1 if changes: return table_differences return False
Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff
entailment