repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
sdispater/eloquent | eloquent/migrations/database_migration_repository.py | DatabaseMigrationRepository.get_last | 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() | python | 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() | [
"def",
"get_last",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"table",
"(",
")",
".",
"where",
"(",
"'batch'",
",",
"self",
".",
"get_last_batch_number",
"(",
")",
")",
"return",
"query",
".",
"order_by",
"(",
"'migration'",
",",
"'desc'",
")",
".",
"get",
"(",
")"
] | Get the last migration batch.
:rtype: list | [
"Get",
"the",
"last",
"migration",
"batch",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/database_migration_repository.py#L25-L33 |
sdispater/eloquent | eloquent/query/grammars/grammar.py | QueryGrammar.compile_insert | 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) | python | 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) | [
"def",
"compile_insert",
"(",
"self",
",",
"query",
",",
"values",
")",
":",
"# 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 | [
"Compile",
"an",
"insert",
"SQL",
"statement"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/grammar.py#L312-L344 |
sdispater/eloquent | eloquent/dbal/platforms/postgres_platform.py | PostgresPlatform.get_alter_table_sql | 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 | python | 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 | [
"def",
"get_alter_table_sql",
"(",
"self",
",",
"diff",
")",
":",
"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 | [
"Get",
"the",
"ALTER",
"TABLE",
"SQL",
"statement"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/platforms/postgres_platform.py#L117-L180 |
sdispater/eloquent | eloquent/query/grammars/sqlite_grammar.py | SQLiteQueryGrammar._date_based_where | 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) | python | 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) | [
"def",
"_date_based_where",
"(",
"self",
",",
"type",
",",
"query",
",",
"where",
")",
":",
"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 | [
"Compiled",
"a",
"date",
"where",
"based",
"clause"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/sqlite_grammar.py#L114-L135 |
sdispater/eloquent | eloquent/query/grammars/mysql_grammar.py | MySqlQueryGrammar.compile_select | 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 | python | 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 | [
"def",
"compile_select",
"(",
"self",
",",
"query",
")",
":",
"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 | [
"Compile",
"a",
"select",
"query",
"into",
"SQL"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L23-L38 |
sdispater/eloquent | eloquent/query/grammars/mysql_grammar.py | MySqlQueryGrammar._compile_lock | 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' | python | 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' | [
"def",
"_compile_lock",
"(",
"self",
",",
"query",
",",
"value",
")",
":",
"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 | [
"Compile",
"the",
"lock",
"into",
"SQL"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L57-L76 |
sdispater/eloquent | eloquent/query/grammars/mysql_grammar.py | MySqlQueryGrammar.compile_update | 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() | python | 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() | [
"def",
"compile_update",
"(",
"self",
",",
"query",
",",
"values",
")",
":",
"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 | [
"Compile",
"an",
"update",
"statement",
"into",
"SQL"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L78-L99 |
sdispater/eloquent | eloquent/support/collection.py | Collection.collapse | 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) | python | 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) | [
"def",
"collapse",
"(",
"self",
")",
":",
"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 | [
"Collapse",
"the",
"collection",
"items",
"into",
"a",
"single",
"element",
"(",
"dict",
"or",
"list",
")"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L50-L68 |
sdispater/eloquent | eloquent/support/collection.py | Collection.contains | 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 | python | 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 | [
"def",
"contains",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
")",
":",
"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 | [
"Determine",
"if",
"an",
"element",
"is",
"in",
"the",
"collection"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L70-L89 |
sdispater/eloquent | eloquent/support/collection.py | Collection.lists | 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) | python | 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) | [
"def",
"lists",
"(",
"self",
",",
"value",
",",
"key",
"=",
"None",
")",
":",
"results",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"value",
"]",
",",
"self",
".",
"_items",
")",
"return",
"list",
"(",
"results",
")"
] | Get a list with the values of a given key
:rtype: list | [
"Get",
"a",
"list",
"with",
"the",
"values",
"of",
"a",
"given",
"key"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L118-L126 |
sdispater/eloquent | eloquent/support/collection.py | Collection.map | 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))) | python | 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))) | [
"def",
"map",
"(",
"self",
",",
"callback",
")",
":",
"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 | [
"Run",
"a",
"map",
"over",
"each",
"of",
"the",
"item",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L128-L140 |
sdispater/eloquent | eloquent/support/collection.py | Collection.unique | 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))]) | python | 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))]) | [
"def",
"unique",
"(",
"self",
")",
":",
"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 | [
"Return",
"only",
"unique",
"items",
"from",
"the",
"collection",
"list",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L142-L151 |
sdispater/eloquent | eloquent/orm/collection.py | Collection.load | 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 | python | 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 | [
"def",
"load",
"(",
"self",
",",
"*",
"relations",
")",
":",
"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. | [
"Load",
"a",
"set",
"of",
"relationships",
"onto",
"the",
"collection",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/collection.py#L8-L17 |
sdispater/eloquent | eloquent/schema/grammars/grammar.py | SchemaGrammar.compile_foreign | 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 | python | 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 | [
"def",
"compile_foreign",
"(",
"self",
",",
"blueprint",
",",
"command",
",",
"_",
")",
":",
"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 | [
"Compile",
"a",
"foreign",
"key",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L73-L105 |
sdispater/eloquent | eloquent/schema/grammars/grammar.py | SchemaGrammar._get_columns | 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 | python | 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 | [
"def",
"_get_columns",
"(",
"self",
",",
"blueprint",
")",
":",
"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 | [
"Get",
"the",
"blueprint",
"s",
"columns",
"definitions",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L107-L123 |
sdispater/eloquent | eloquent/schema/grammars/grammar.py | SchemaGrammar._add_modifiers | 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 | python | 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 | [
"def",
"_add_modifiers",
"(",
"self",
",",
"sql",
",",
"blueprint",
",",
"column",
")",
":",
"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 | [
"Add",
"the",
"column",
"modifiers",
"to",
"the",
"deifinition"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L125-L135 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany._clean_pivot_attributes | 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 | python | 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 | [
"def",
"_clean_pivot_attributes",
"(",
"self",
",",
"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 | [
"Get",
"the",
"pivot",
"attributes",
"from",
"a",
"model",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L155-L173 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany.get_relation_count_query_for_self_join | 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)) | python | 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)) | [
"def",
"get_relation_count_query_for_self_join",
"(",
"self",
",",
"query",
",",
"parent",
")",
":",
"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 | [
"Add",
"the",
"constraints",
"for",
"a",
"relationship",
"count",
"query",
"on",
"the",
"same",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L202-L220 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany._get_select_columns | 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() | python | 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() | [
"def",
"_get_select_columns",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"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 | [
"Set",
"the",
"select",
"clause",
"for",
"the",
"relation",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L230-L242 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany._get_aliased_pivot_columns | 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 | python | 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 | [
"def",
"_get_aliased_pivot_columns",
"(",
"self",
")",
":",
"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 | [
"Get",
"the",
"pivot",
"columns",
"for",
"the",
"relation",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L244-L259 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany._set_join | 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 | python | 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 | [
"def",
"_set_join",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"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 | [
"Set",
"the",
"join",
"clause",
"for",
"the",
"relation",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L272-L291 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany.match | 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 | python | 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 | [
"def",
"match",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
")",
":",
"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 | [
"Match",
"the",
"eagerly",
"loaded",
"results",
"to",
"their",
"parents",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L326-L344 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany.save | 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 | python | 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 | [
"def",
"save",
"(",
"self",
",",
"model",
",",
"joining",
"=",
"None",
",",
"touch",
"=",
"True",
")",
":",
"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 | [
"Save",
"a",
"new",
"model",
"and",
"attach",
"it",
"to",
"the",
"parent",
"model",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L393-L410 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany._attach_new | 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 | python | 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 | [
"def",
"_attach_new",
"(",
"self",
",",
"records",
",",
"current",
",",
"touch",
"=",
"True",
")",
":",
"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. | [
"Attach",
"all",
"of",
"the",
"IDs",
"that",
"aren",
"t",
"in",
"the",
"current",
"dict",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L595-L612 |
sdispater/eloquent | eloquent/orm/relations/belongs_to_many.py | BelongsToMany.update_existing_pivot | 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 | python | 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 | [
"def",
"update_existing_pivot",
"(",
"self",
",",
"id",
",",
"attributes",
",",
"touch",
"=",
"True",
")",
":",
"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. | [
"Update",
"an",
"existing",
"pivot",
"record",
"on",
"the",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L614-L626 |
sdispater/eloquent | eloquent/connections/connection.py | Connection.query | def query(self):
"""
Begin a fluent query
:return: A QueryBuilder instance
:rtype: QueryBuilder
"""
query = QueryBuilder(self, self._query_grammar, self._post_processor)
return query | python | def query(self):
"""
Begin a fluent query
:return: A QueryBuilder instance
:rtype: QueryBuilder
"""
query = QueryBuilder(self, self._query_grammar, self._post_processor)
return query | [
"def",
"query",
"(",
"self",
")",
":",
"query",
"=",
"QueryBuilder",
"(",
"self",
",",
"self",
".",
"_query_grammar",
",",
"self",
".",
"_post_processor",
")",
"return",
"query"
] | Begin a fluent query
:return: A QueryBuilder instance
:rtype: QueryBuilder | [
"Begin",
"a",
"fluent",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/connections/connection.py#L108-L117 |
sdispater/eloquent | eloquent/orm/mixins/soft_deletes.py | SoftDeletes.force_delete | def force_delete(self):
"""
Force a hard delete on a soft deleted model.
"""
self._force_deleting = True
self.delete()
self._force_deleting = False | python | def force_delete(self):
"""
Force a hard delete on a soft deleted model.
"""
self._force_deleting = True
self.delete()
self._force_deleting = False | [
"def",
"force_delete",
"(",
"self",
")",
":",
"self",
".",
"_force_deleting",
"=",
"True",
"self",
".",
"delete",
"(",
")",
"self",
".",
"_force_deleting",
"=",
"False"
] | Force a hard delete on a soft deleted model. | [
"Force",
"a",
"hard",
"delete",
"on",
"a",
"soft",
"deleted",
"model",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/mixins/soft_deletes.py#L17-L25 |
sdispater/eloquent | eloquent/orm/mixins/soft_deletes.py | SoftDeletes._do_perform_delete_on_model | 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() | python | 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() | [
"def",
"_do_perform_delete_on_model",
"(",
"self",
")",
":",
"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. | [
"Perform",
"the",
"actual",
"delete",
"query",
"on",
"this",
"model",
"instance",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/mixins/soft_deletes.py#L27-L34 |
sdispater/eloquent | eloquent/orm/mixins/soft_deletes.py | SoftDeletes.restore | 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 | python | 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 | [
"def",
"restore",
"(",
"self",
")",
":",
"setattr",
"(",
"self",
",",
"self",
".",
"get_deleted_at_column",
"(",
")",
",",
"None",
")",
"self",
".",
"set_exists",
"(",
"True",
")",
"result",
"=",
"self",
".",
"save",
"(",
")",
"return",
"result"
] | Restore a soft-deleted model instance. | [
"Restore",
"a",
"soft",
"-",
"deleted",
"model",
"instance",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/mixins/soft_deletes.py#L49-L59 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.join | 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 | python | 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 | [
"def",
"join",
"(",
"self",
",",
"table",
",",
"one",
"=",
"None",
",",
"operator",
"=",
"None",
",",
"two",
"=",
"None",
",",
"type",
"=",
"'inner'",
",",
"where",
"=",
"False",
")",
":",
"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 | [
"Add",
"a",
"join",
"clause",
"to",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L168-L206 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.join_where | 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) | python | 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) | [
"def",
"join_where",
"(",
"self",
",",
"table",
",",
"one",
",",
"operator",
",",
"two",
",",
"type",
"=",
"'inner'",
")",
":",
"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 | [
"Add",
"a",
"join",
"where",
"clause",
"to",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L208-L230 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder._where_in_sub | 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 | python | 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 | [
"def",
"_where_in_sub",
"(",
"self",
",",
"column",
",",
"query",
",",
"boolean",
",",
"negate",
"=",
"False",
")",
":",
"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 | [
"Add",
"a",
"where",
"in",
"with",
"a",
"sub",
"select",
"to",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L521-L554 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.or_having | 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') | python | 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') | [
"def",
"or_having",
"(",
"self",
",",
"column",
",",
"operator",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"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 | [
"Add",
"a",
"having",
"clause",
"to",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L676-L692 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.union | 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) | python | 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) | [
"def",
"union",
"(",
"self",
",",
"query",
",",
"all",
"=",
"False",
")",
":",
"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 | [
"Add",
"a",
"union",
"statement",
"to",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L850-L868 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.find | 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) | python | 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) | [
"def",
"find",
"(",
"self",
",",
"id",
",",
"columns",
"=",
"None",
")",
":",
"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 | [
"Execute",
"a",
"query",
"for",
"a",
"single",
"record",
"by",
"id"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L923-L939 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.first | 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 | python | 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 | [
"def",
"first",
"(",
"self",
",",
"limit",
"=",
"1",
",",
"columns",
"=",
"None",
")",
":",
"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 | [
"Execute",
"the",
"query",
"and",
"get",
"the",
"first",
"results"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L958-L979 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.get_fresh | 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()) | python | 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()) | [
"def",
"get_fresh",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"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 | [
"Execute",
"the",
"query",
"as",
"a",
"fresh",
"select",
"statement"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L996-L1012 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder._get_list_select | 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 | python | 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 | [
"def",
"_get_list_select",
"(",
"self",
",",
"column",
",",
"key",
"=",
"None",
")",
":",
"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 | [
"Get",
"the",
"columns",
"that",
"should",
"be",
"used",
"in",
"a",
"list"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1071-L1098 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.increment | 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) | python | 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) | [
"def",
"increment",
"(",
"self",
",",
"column",
",",
"amount",
"=",
"1",
",",
"extras",
"=",
"None",
")",
":",
"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 | [
"Increment",
"a",
"column",
"s",
"value",
"by",
"a",
"given",
"amount"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1309-L1335 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.delete | 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()) | python | 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()) | [
"def",
"delete",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"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 | [
"Delete",
"a",
"record",
"from",
"the",
"database"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1365-L1380 |
sdispater/eloquent | eloquent/query/builder.py | QueryBuilder.merge_wheres | 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 | python | 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 | [
"def",
"merge_wheres",
"(",
"self",
",",
"wheres",
",",
"bindings",
")",
":",
"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 | [
"Merge",
"a",
"list",
"of",
"where",
"clauses",
"and",
"bindings"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1400-L1413 |
sdispater/eloquent | eloquent/commands/migrations/make_command.py | MigrateMakeCommand.execute | 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_) | python | 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_) | [
"def",
"execute",
"(",
"self",
",",
"i",
",",
"o",
")",
":",
"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 | [
"Executes",
"the",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/commands/migrations/make_command.py#L24-L48 |
sdispater/eloquent | eloquent/orm/scopes/soft_deleting.py | SoftDeletingScope.remove | 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 | python | 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 | [
"def",
"remove",
"(",
"self",
",",
"builder",
",",
"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 | [
"Remove",
"the",
"scope",
"from",
"a",
"given",
"query",
"builder",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/scopes/soft_deleting.py#L24-L47 |
sdispater/eloquent | eloquent/orm/scopes/soft_deleting.py | SoftDeletingScope.extend | 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) | python | 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) | [
"def",
"extend",
"(",
"self",
",",
"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 | [
"Extend",
"the",
"query",
"builder",
"with",
"the",
"needed",
"functions",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/scopes/soft_deleting.py#L49-L59 |
sdispater/eloquent | eloquent/orm/scopes/soft_deleting.py | SoftDeletingScope._only_trashed | 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()) | python | 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()) | [
"def",
"_only_trashed",
"(",
"self",
",",
"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 | [
"The",
"only",
"-",
"trashed",
"extension",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/scopes/soft_deleting.py#L157-L168 |
sdispater/eloquent | eloquent/schema/blueprint.py | Blueprint._add_fluent_indexes | 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 | python | 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 | [
"def",
"_add_fluent_indexes",
"(",
"self",
")",
":",
"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: | [
"Add",
"the",
"index",
"commands",
"fluently",
"specified",
"on",
"columns",
":"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/blueprint.py#L74-L89 |
sdispater/eloquent | eloquent/schema/blueprint.py | Blueprint.big_integer | 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) | python | 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) | [
"def",
"big_integer",
"(",
"self",
",",
"column",
",",
"auto_increment",
"=",
"False",
",",
"unsigned",
"=",
"False",
")",
":",
"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 | [
"Create",
"a",
"new",
"big",
"integer",
"column",
"on",
"the",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/blueprint.py#L376-L391 |
sdispater/eloquent | eloquent/schema/blueprint.py | Blueprint.medium_integer | 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) | python | 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) | [
"def",
"medium_integer",
"(",
"self",
",",
"column",
",",
"auto_increment",
"=",
"False",
",",
"unsigned",
"=",
"False",
")",
":",
"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 | [
"Create",
"a",
"new",
"medium",
"integer",
"column",
"on",
"the",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/blueprint.py#L393-L408 |
sdispater/eloquent | eloquent/schema/blueprint.py | Blueprint.tiny_integer | 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) | python | 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) | [
"def",
"tiny_integer",
"(",
"self",
",",
"column",
",",
"auto_increment",
"=",
"False",
",",
"unsigned",
"=",
"False",
")",
":",
"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 | [
"Create",
"a",
"new",
"tiny",
"integer",
"column",
"on",
"the",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/blueprint.py#L410-L425 |
sdispater/eloquent | eloquent/schema/blueprint.py | Blueprint._add_column | 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 | python | 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 | [
"def",
"_add_column",
"(",
"self",
",",
"type",
",",
"name",
",",
"*",
"*",
"parameters",
")",
":",
"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 | [
"Add",
"a",
"new",
"column",
"to",
"the",
"blueprint",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/blueprint.py#L698-L721 |
sdispater/eloquent | eloquent/dbal/platforms/sqlite_platform.py | SQLitePlatform.get_alter_table_sql | 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 | python | 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 | [
"def",
"get_alter_table_sql",
"(",
"self",
",",
"diff",
")",
":",
"#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 | [
"Get",
"the",
"ALTER",
"TABLE",
"SQL",
"statement"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/platforms/sqlite_platform.py#L60-L141 |
sdispater/eloquent | eloquent/dbal/platforms/sqlite_platform.py | SQLitePlatform.get_foreign_keys_in_altered_table | 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 | python | 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 | [
"def",
"get_foreign_keys_in_altered_table",
"(",
"self",
",",
"diff",
")",
":",
"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 | [
":",
"param",
"diff",
":",
"The",
"table",
"diff",
":",
"type",
"diff",
":",
"eloquent",
".",
"dbal",
".",
"table_diff",
".",
"TableDiff"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/platforms/sqlite_platform.py#L181-L207 |
sdispater/eloquent | eloquent/orm/relations/belongs_to.py | BelongsTo.get_relation_count_query | 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)) | python | 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)) | [
"def",
"get_relation_count_query",
"(",
"self",
",",
"query",
",",
"parent",
")",
":",
"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 | [
"Add",
"the",
"constraints",
"for",
"a",
"relationship",
"count",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to.py#L49-L62 |
sdispater/eloquent | eloquent/orm/relations/belongs_to.py | BelongsTo.match | 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 | python | 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 | [
"def",
"match",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
")",
":",
"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 | [
"Match",
"the",
"eagerly",
"loaded",
"results",
"to",
"their",
"parents",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to.py#L107-L130 |
sdispater/eloquent | eloquent/orm/relations/belongs_to.py | BelongsTo.associate | 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) | python | 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) | [
"def",
"associate",
"(",
"self",
",",
"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 | [
"Associate",
"the",
"model",
"instance",
"to",
"the",
"given",
"parent",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to.py#L132-L142 |
sdispater/eloquent | eloquent/orm/relations/belongs_to.py | BelongsTo.dissociate | 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) | python | 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) | [
"def",
"dissociate",
"(",
"self",
")",
":",
"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 | [
"Dissociate",
"previously",
"associated",
"model",
"from",
"the",
"given",
"parent",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to.py#L144-L152 |
sdispater/eloquent | eloquent/commands/migrations/status_command.py | StatusCommand.execute | 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) | python | 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) | [
"def",
"execute",
"(",
"self",
",",
"i",
",",
"o",
")",
":",
"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 | [
"Executes",
"the",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/commands/migrations/status_command.py#L20-L62 |
sdispater/eloquent | eloquent/schema/grammars/sqlite_grammar.py | SQLiteSchemaGrammar.compile_rename_column | 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 | python | 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 | [
"def",
"compile_rename_column",
"(",
"self",
",",
"blueprint",
",",
"command",
",",
"connection",
")",
":",
"# 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 | [
"Compile",
"a",
"rename",
"column",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/sqlite_grammar.py#L15-L156 |
sdispater/eloquent | eloquent/schema/grammars/sqlite_grammar.py | SQLiteSchemaGrammar.compile_change | 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 | python | 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 | [
"def",
"compile_change",
"(",
"self",
",",
"blueprint",
",",
"command",
",",
"connection",
")",
":",
"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 | [
"Compile",
"a",
"change",
"column",
"command",
"into",
"a",
"series",
"of",
"SQL",
"statement",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/sqlite_grammar.py#L158-L249 |
sdispater/eloquent | eloquent/schema/grammars/sqlite_grammar.py | SQLiteSchemaGrammar.compile_create | 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 + ')' | python | 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 + ')' | [
"def",
"compile_create",
"(",
"self",
",",
"blueprint",
",",
"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. | [
"Compile",
"a",
"create",
"table",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/sqlite_grammar.py#L265-L277 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany.match_one | 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') | python | 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') | [
"def",
"match_one",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
")",
":",
"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 | [
"Match",
"the",
"eargerly",
"loaded",
"resuls",
"to",
"their",
"single",
"parents",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L42-L57 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany.match_many | 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') | python | 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') | [
"def",
"match_many",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
")",
":",
"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 | [
"Match",
"the",
"eargerly",
"loaded",
"resuls",
"to",
"their",
"single",
"parents",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L59-L74 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany._match_one_or_many | 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 | python | 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 | [
"def",
"_match_one_or_many",
"(",
"self",
",",
"models",
",",
"results",
",",
"relation",
",",
"type",
")",
":",
"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 | [
"Match",
"the",
"eargerly",
"loaded",
"resuls",
"to",
"their",
"single",
"parents",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L76-L104 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany._get_relation_value | 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) | python | 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) | [
"def",
"_get_relation_value",
"(",
"self",
",",
"dictionary",
",",
"key",
",",
"type",
")",
":",
"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 | [
"Get",
"the",
"value",
"of",
"the",
"relationship",
"by",
"one",
"or",
"many",
"type",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L106-L119 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany.first_or_new | 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 | python | 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 | [
"def",
"first_or_new",
"(",
"self",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attributes",
")",
":",
"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 | [
"Get",
"the",
"first",
"related",
"model",
"record",
"matching",
"the",
"attributes",
"or",
"instantiate",
"it",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L193-L211 |
sdispater/eloquent | eloquent/orm/relations/has_one_or_many.py | HasOneOrMany.first_or_create | 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 | python | 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 | [
"def",
"first_or_create",
"(",
"self",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attributes",
")",
":",
"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 | [
"Get",
"the",
"first",
"related",
"record",
"matching",
"the",
"attributes",
"or",
"create",
"it",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/has_one_or_many.py#L213-L230 |
sdispater/eloquent | eloquent/commands/migrations/reset_command.py | ResetCommand.execute | 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 | python | 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 | [
"def",
"execute",
"(",
"self",
",",
"i",
",",
"o",
")",
":",
"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 | [
"Executes",
"the",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/commands/migrations/reset_command.py#L23-L62 |
sdispater/eloquent | eloquent/orm/relations/morph_to_many.py | MorphToMany.get_relation_count_query | 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) | python | 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) | [
"def",
"get_relation_count_query",
"(",
"self",
",",
"query",
",",
"parent",
")",
":",
"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 | [
"Add",
"the",
"constraints",
"for",
"a",
"relationship",
"count",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_to_many.py#L48-L59 |
sdispater/eloquent | eloquent/orm/relations/morph_to_many.py | MorphToMany.add_eager_constraints | 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) | python | 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) | [
"def",
"add_eager_constraints",
"(",
"self",
",",
"models",
")",
":",
"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 | [
"Set",
"the",
"constraints",
"for",
"an",
"eager",
"load",
"of",
"the",
"relation",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_to_many.py#L61-L69 |
sdispater/eloquent | eloquent/orm/relations/morph_to_many.py | MorphToMany._create_attach_record | 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 | python | 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 | [
"def",
"_create_attach_record",
"(",
"self",
",",
"id",
",",
"timed",
")",
":",
"record",
"=",
"super",
"(",
"MorphToMany",
",",
"self",
")",
".",
"_create_attach_record",
"(",
"id",
",",
"timed",
")",
"record",
"[",
"self",
".",
"_morph_type",
"]",
"=",
"self",
".",
"_morph_class",
"return",
"record"
] | Create a new pivot attachement record. | [
"Create",
"a",
"new",
"pivot",
"attachement",
"record",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_to_many.py#L71-L79 |
sdispater/eloquent | eloquent/orm/relations/morph_to_many.py | MorphToMany._new_pivot_query | 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) | python | 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) | [
"def",
"_new_pivot_query",
"(",
"self",
")",
":",
"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 | [
"Create",
"a",
"new",
"query",
"builder",
"for",
"the",
"pivot",
"table",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_to_many.py#L81-L89 |
sdispater/eloquent | eloquent/orm/relations/morph_to_many.py | MorphToMany.new_pivot | 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 | python | 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 | [
"def",
"new_pivot",
"(",
"self",
",",
"attributes",
"=",
"None",
",",
"exists",
"=",
"False",
")",
":",
"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. | [
"Create",
"a",
"new",
"pivot",
"model",
"instance",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_to_many.py#L91-L103 |
sdispater/eloquent | eloquent/commands/migrations/install_command.py | InstallCommand.execute | 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>') | python | 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>') | [
"def",
"execute",
"(",
"self",
",",
"i",
",",
"o",
")",
":",
"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 | [
"Executes",
"the",
"command",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/commands/migrations/install_command.py#L18-L33 |
sdispater/eloquent | eloquent/query/processors/mysql_processor.py | MySqlQueryProcessor.process_insert_get_id | 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 | python | 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 | [
"def",
"process_insert_get_id",
"(",
"self",
",",
"query",
",",
"sql",
",",
"values",
",",
"sequence",
"=",
"None",
")",
":",
"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 | [
"Process",
"an",
"insert",
"get",
"ID",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/processors/mysql_processor.py#L8-L51 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.chunk | 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() | python | 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() | [
"def",
"chunk",
"(",
"self",
",",
"count",
")",
":",
"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 | [
"Chunk",
"the",
"results",
"of",
"the",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L167-L185 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.lists | 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 | python | 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 | [
"def",
"lists",
"(",
"self",
",",
"column",
",",
"key",
"=",
"None",
")",
":",
"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 | [
"Get",
"a",
"list",
"with",
"the",
"values",
"of",
"a",
"given",
"column"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L187-L214 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.increment | 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) | python | 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) | [
"def",
"increment",
"(",
"self",
",",
"column",
",",
"amount",
"=",
"1",
",",
"extras",
"=",
"None",
")",
":",
"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 | [
"Increment",
"a",
"column",
"s",
"value",
"by",
"a",
"given",
"amount"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L259-L277 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.decrement | 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) | python | 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) | [
"def",
"decrement",
"(",
"self",
",",
"column",
",",
"amount",
"=",
"1",
",",
"extras",
"=",
"None",
")",
":",
"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 | [
"Decrement",
"a",
"column",
"s",
"value",
"by",
"a",
"given",
"amount"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L279-L297 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.get_models | 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() | python | 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() | [
"def",
"get_models",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"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 | [
"Get",
"the",
"hydrated",
"models",
"without",
"eager",
"loading",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L342-L356 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.eager_load_relations | 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 | python | 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 | [
"def",
"eager_load_relations",
"(",
"self",
",",
"models",
")",
":",
"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 | [
"Eager",
"load",
"the",
"relationship",
"of",
"the",
"models",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L358-L372 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._load_relation | 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) | python | 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) | [
"def",
"_load_relation",
"(",
"self",
",",
"models",
",",
"name",
",",
"constraints",
")",
":",
"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 | [
"Eagerly",
"load",
"the",
"relationship",
"on",
"a",
"set",
"of",
"models",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L374-L393 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._has_nested | 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) | python | 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) | [
"def",
"_has_nested",
"(",
"self",
",",
"relations",
",",
"operator",
"=",
"'>='",
",",
"count",
"=",
"1",
",",
"boolean",
"=",
"'and'",
",",
"extra",
"=",
"None",
")",
":",
"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 | [
"Add",
"nested",
"relationship",
"count",
"conditions",
"to",
"the",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L518-L547 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.doesnt_have | 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) | python | 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) | [
"def",
"doesnt_have",
"(",
"self",
",",
"relation",
",",
"boolean",
"=",
"'and'",
",",
"extra",
"=",
"None",
")",
":",
"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 | [
"Add",
"a",
"relationship",
"count",
"to",
"the",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L549-L564 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.where_has | 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) | python | 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) | [
"def",
"where_has",
"(",
"self",
",",
"relation",
",",
"extra",
",",
"operator",
"=",
"'>='",
",",
"count",
"=",
"1",
")",
":",
"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 | [
"Add",
"a",
"relationship",
"count",
"condition",
"to",
"the",
"query",
"with",
"where",
"clauses",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L566-L584 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.or_has | 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') | python | 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') | [
"def",
"or_has",
"(",
"self",
",",
"relation",
",",
"operator",
"=",
"'>='",
",",
"count",
"=",
"1",
")",
":",
"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 | [
"Add",
"a",
"relationship",
"count",
"condition",
"to",
"the",
"query",
"with",
"an",
"or",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L600-L615 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.or_where_has | 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) | python | 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) | [
"def",
"or_where_has",
"(",
"self",
",",
"relation",
",",
"extra",
",",
"operator",
"=",
"'>='",
",",
"count",
"=",
"1",
")",
":",
"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 | [
"Add",
"a",
"relationship",
"count",
"condition",
"to",
"the",
"query",
"with",
"where",
"clauses",
"and",
"an",
"or",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L617-L635 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._merge_wheres_to_has | 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()) | python | 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()) | [
"def",
"_merge_wheres_to_has",
"(",
"self",
",",
"has_query",
",",
"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 | [
"Merge",
"the",
"wheres",
"from",
"the",
"relation",
"query",
"to",
"a",
"has",
"query",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L665-L679 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._get_has_relation_query | 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)()
) | python | 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)()
) | [
"def",
"_get_has_relation_query",
"(",
"self",
",",
"relation",
")",
":",
"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 | [
"Get",
"the",
"has",
"relation",
"base",
"query"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L681-L693 |
sdispater/eloquent | eloquent/orm/builder.py | Builder.with_ | 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 | python | 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 | [
"def",
"with_",
"(",
"self",
",",
"*",
"relations",
")",
":",
"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 | [
"Set",
"the",
"relationships",
"that",
"should",
"be",
"eager",
"loaded",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L695-L709 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._parse_relations | 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 | python | 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 | [
"def",
"_parse_relations",
"(",
"self",
",",
"relations",
")",
":",
"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 | [
"Parse",
"a",
"list",
"of",
"relations",
"into",
"individuals",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L711-L734 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._parse_nested | 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 | python | 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 | [
"def",
"_parse_nested",
"(",
"self",
",",
"name",
",",
"results",
")",
":",
"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 | [
"Parse",
"the",
"nested",
"relationship",
"in",
"a",
"relation",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L736-L756 |
sdispater/eloquent | eloquent/orm/builder.py | Builder._call_scope | 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 | python | 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 | [
"def",
"_call_scope",
"(",
"self",
",",
"scope",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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 | [
"Call",
"the",
"given",
"model",
"scope",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L758-L767 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator._run_up | 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) | python | 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) | [
"def",
"_run_up",
"(",
"self",
",",
"path",
",",
"migration_file",
",",
"batch",
",",
"pretend",
"=",
"False",
")",
":",
"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' %",
"m",
"gration_file)",
""
] | Run "up" a migration instance.
:type migration_file: str
:type batch: int
:type pretend: bool | [
"Run",
"up",
"a",
"migration",
"instance",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L69-L88 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator.rollback | 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) | python | 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) | [
"def",
"rollback",
"(",
"self",
",",
"path",
",",
"pretend",
"=",
"False",
")",
":",
"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 | [
"Rollback",
"the",
"last",
"migration",
"operation",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L90-L114 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator._run_down | 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) | python | 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) | [
"def",
"_run_down",
"(",
"self",
",",
"path",
",",
"migration",
",",
"pretend",
"=",
"False",
")",
":",
"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' %",
"m",
"gration_file)",
""
] | Run "down" a migration instance. | [
"Run",
"down",
"a",
"migration",
"instance",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L116-L131 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator._pretend_to_run | 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)) | python | 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)) | [
"def",
"_pretend_to_run",
"(",
"self",
",",
"migration",
",",
"method",
")",
":",
"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 | [
"Pretend",
"to",
"run",
"the",
"migration",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L152-L165 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator._get_queries | 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 | python | 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 | [
"def",
"_get_queries",
"(",
"self",
",",
"migration",
",",
"method",
")",
":",
"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 | [
"Get",
"all",
"of",
"the",
"queries",
"that",
"would",
"be",
"run",
"for",
"a",
"migration",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L167-L195 |
sdispater/eloquent | eloquent/migrations/migrator.py | Migrator._resolve | 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 | python | 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 | [
"def",
"_resolve",
"(",
"self",
",",
"path",
",",
"migration_file",
")",
":",
"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 | [
"Resolve",
"a",
"migration",
"instance",
"from",
"a",
"file",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migrator.py#L197-L219 |
sdispater/eloquent | eloquent/dbal/platforms/mysql_platform.py | MySqlPlatform.get_alter_table_sql | 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 | python | 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 | [
"def",
"get_alter_table_sql",
"(",
"self",
",",
"diff",
")",
":",
"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 | [
"Get",
"the",
"ALTER",
"TABLE",
"SQL",
"statement"
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/platforms/mysql_platform.py#L85-L129 |
sdispater/eloquent | eloquent/dbal/comparator.py | Comparator.diff_table | 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 | python | 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 | [
"def",
"diff_table",
"(",
"self",
",",
"table1",
",",
"table2",
")",
":",
"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 | [
"Returns",
"the",
"difference",
"between",
"the",
"tables",
"table1",
"and",
"table2",
"."
] | train | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/comparator.py#L12-L110 |
Subsets and Splits