Python sqlalchemy.types.Integer() Examples
The following are 30
code examples of sqlalchemy.types.Integer().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sqlalchemy.types
, or try the search function
.
Example #1
Source File: annotation_database_parser.py From HistomicsTK with Apache License 2.0 | 6 votes |
def _add_annotation_elements_to_sqlite(dbcon, annotation_elements): # drop index relative to JSON since its pretty arbitrary and would # change if the same girder client was used to get annotations twice # the actual girder ID string is what really matters and should be used annotation_elements.drop( labels=['annidx', 'elementidx'], axis=1, inplace=True) annotation_elements.to_sql( name='annotation_elements', con=dbcon, if_exists='append', dtype={ 'annotation_girder_id': String(), 'element_girder_id': String(), 'type': String(), 'group': String(), 'label': String(), 'color': String(), 'xmin': Integer(), 'xmax': Integer(), 'ymin': Integer(), 'ymax': Integer(), 'bbox_area': Integer(), 'coords_x': String(), 'coords_y': String(), }, index=False, )
Example #2
Source File: annotation_database_parser.py From HistomicsTK with Apache License 2.0 | 6 votes |
def _add_annotation_docs_to_sqlite(dbcon, annotation_docs, item): # add full item path for convenience annotation_docs.loc[:, "item_name"] = item['name'] # save tables to sqlite annotation_docs.to_sql( name='annotation_docs', con=dbcon, if_exists='append', dtype={ 'annotation_girder_id': String(), '_modelType': String(), '_version': Integer(), 'itemId': String(), 'item_name': String(), 'created': String(), 'creatorId': String(), 'public': Boolean(), 'updated': String(), 'updatedId': String(), 'groups': String(), 'element_count': Integer(), 'element_details': Integer(), }, index=False, )
Example #3
Source File: DataModelClasses.py From marvin with BSD 3-Clause "New" or "Revised" License | 6 votes |
def set_quality(stage): ''' produces cube quality flag ''' col = 'DRP2QUAL' if stage == '2d' else 'DRP3QUAL' label = 'cubequal{0}'.format(stage) kwarg = 'DRP{0}QUAL'.format(stage[0]) @hybrid_property def quality(self): bits = self.getQualBits(stage=stage) return int(bits) @quality.expression def quality(cls): return select([FitsHeaderValue.value.cast(Integer)]).\ where(and_(FitsHeaderKeyword.pk==FitsHeaderValue.fits_header_keyword_pk, FitsHeaderKeyword.label.ilike(kwarg), FitsHeaderValue.cube_pk==cls.pk)).\ label(label) return quality
Example #4
Source File: DataModelClasses.py From marvin with BSD 3-Clause "New" or "Revised" License | 6 votes |
def set_manga_target(targtype): ''' produces manga_target flags ''' label = 'mngtrg{0}'.format(targtype) kwarg = 'MNGT%RG{0}'.format(targtype) @hybrid_property def target(self): bits = self.getTargBits(targtype=targtype) return int(bits) @target.expression def target(cls): return select([FitsHeaderValue.value.cast(Integer)]).\ where(and_(FitsHeaderKeyword.pk==FitsHeaderValue.fits_header_keyword_pk, FitsHeaderKeyword.label.ilike(kwarg), FitsHeaderValue.cube_pk==cls.pk)).\ label(label) return target
Example #5
Source File: mysql.py From stdm with GNU General Public License v2.0 | 6 votes |
def visit_column(self, delta): table = delta.table colspec = self.get_column_specification(delta.result_column) if delta.result_column.autoincrement: primary_keys = [c for c in table.primary_key.columns if (c.autoincrement and isinstance(c.type, sqltypes.Integer) and not c.foreign_keys)] if primary_keys: first = primary_keys.pop(0) if first.name == delta.current_name: colspec += " AUTO_INCREMENT" q = util.safe_quote(table) old_col_name = self.preparer.quote(delta.current_name, q) self.start_alter_table(table) self.append("CHANGE COLUMN %s " % old_col_name) self.append(colspec) self.execute()
Example #6
Source File: whoosh_backend.py From flask-msearch with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fields_map(self, field_type): if field_type == "primary": return ID(stored=True, unique=True) type_map = { 'date': types.Date, 'datetime': types.DateTime, 'boolean': types.Boolean, 'integer': types.Integer, 'float': types.Float } if isinstance(field_type, str): field_type = type_map.get(field_type, types.Text) if not isinstance(field_type, type): field_type = field_type.__class__ if issubclass(field_type, (types.DateTime, types.Date)): return DATETIME(stored=True, sortable=True) elif issubclass(field_type, types.Integer): return NUMERIC(stored=True, numtype=int) elif issubclass(field_type, types.Float): return NUMERIC(stored=True, numtype=float) elif issubclass(field_type, types.Boolean): return BOOLEAN(stored=True) return TEXT(stored=True, analyzer=self.analyzer, sortable=False)
Example #7
Source File: DapModelClasses.py From marvin with BSD 3-Clause "New" or "Revised" License | 6 votes |
def spaxel_factory(classname, clean=None): ''' class factory for the spaxelprop tables ''' if clean: classname = 'Clean{0}'.format(classname) tablename = classname.lower() params = {'__tablename__': tablename, '__table_args__': {'autoload': True, 'schema': 'mangadapdb'}} if clean: params.update({'pk': Column(Integer, primary_key=True)}) def newrepr(self): return '<{2} (pk={0}, file={1})'.format(self.pk, self.file_pk, classname) try: newclass = type(classname, (Base, SpaxelAtts,), params) newclass.__repr__ = newrepr except Exception as e: newclass = None return newclass # create the (clean)spaxel models from the DAP datamodel
Example #8
Source File: type_api.py From sqlalchemy with MIT License | 5 votes |
def _adapt_expression(self, op, other_comparator): """evaluate the return type of <self> <op> <othertype>, and apply any adaptations to the given operator. This method determines the type of a resulting binary expression given two source types and an operator. For example, two :class:`_schema.Column` objects, both of the type :class:`.Integer`, will produce a :class:`.BinaryExpression` that also has the type :class:`.Integer` when compared via the addition (``+``) operator. However, using the addition operator with an :class:`.Integer` and a :class:`.Date` object will produce a :class:`.Date`, assuming "days delta" behavior by the database (in reality, most databases other than PostgreSQL don't accept this particular operation). The method returns a tuple of the form <operator>, <type>. The resulting operator and type will be those applied to the resulting :class:`.BinaryExpression` as the final operator and the right-hand side of the expression. Note that only a subset of operators make usage of :meth:`._adapt_expression`, including math operators and user-defined operators, but not boolean comparison or special SQL keywords like MATCH or BETWEEN. """ return op, self.type
Example #9
Source File: annotation_database_parser.py From HistomicsTK with Apache License 2.0 | 5 votes |
def _add_folder_to_sqlite(dbcon, folder_info): # modify folder info to prep for appending to sqlite table folder_info_dtypes = { '_accessLevel': Integer(), '_id': String(), '_modelType': String(), 'baseParentId': String(), 'baseParentType': String(), 'created': String(), 'creatorId': String(), 'description': String(), 'name': String(), 'parentCollection': String(), 'parentId': String(), 'public': Boolean(), 'size': Integer(), 'updated': String(), 'folder_path': String(), } # in case anything is not in the schema, drop it folder_info = { k: v for k, v in folder_info.items() if k in folder_info_dtypes.keys()} # convert to df and add to items table folder_info_df = DataFrame.from_dict(folder_info, orient='index').T folder_info_df.to_sql( name='folders', con=dbcon, if_exists='append', dtype=folder_info_dtypes, index=False)
Example #10
Source File: test_reflection.py From stdm with GNU General Public License v2.0 | 5 votes |
def define_tables(cls, metadata): Table('test_table', metadata, Column('id', Integer, primary_key=True), Column('data', String(50)) )
Example #11
Source File: netezza_dialect.py From netezza_sqlalchemy with MIT License | 5 votes |
def get_columns(self, connection, table_name, schema=None, **kw): SQL_COLS = """ SELECT CAST(a.attname AS VARCHAR(128)) as name, a.atttypid as typeid, not a.attnotnull as nullable, a.attcolleng as length, a.format_type FROM _v_relation_column a WHERE a.name = :tablename ORDER BY a.attnum """ s = text(SQL_COLS, bindparams=[bindparam('tablename', type_=sqltypes.String)], typemap={'name': NAME, 'typeid': sqltypes.Integer, 'nullable': sqltypes.Boolean, 'length': sqltypes.Integer, 'format_type': sqltypes.String, }) c = connection.execute(s, tablename=table_name) rows = c.fetchall() # format columns columns = [] for name, typeid, nullable, length, format_type in rows: coltype_class, has_length = oid_datatype_map[typeid] if coltype_class is sqltypes.Numeric: precision, scale = re.match( r'numeric\((\d+),(\d+)\)', format_type).groups() coltype = coltype_class(int(precision), int(scale)) elif has_length: coltype = coltype_class(length) else: coltype = coltype_class() columns.append({ 'name': name, 'type': coltype, 'nullable': nullable, }) return columns
Example #12
Source File: test_jsonify.py From pecan with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_sa_proxies(self): # create the table and mapper metadata = schema.MetaData() user_table = schema.Table( 'user', metadata, schema.Column('id', types.Integer, primary_key=True), schema.Column('first_name', types.Unicode(25)), schema.Column('last_name', types.Unicode(25)) ) class User(object): pass orm.mapper(User, user_table) # create the session engine = create_engine('sqlite:///:memory:') metadata.bind = engine metadata.create_all() session = orm.sessionmaker(bind=engine)() # add some dummy data user_table.insert().execute([ {'first_name': 'Jonathan', 'last_name': 'LaCour'}, {'first_name': 'Yoann', 'last_name': 'Roman'} ]) # get the SA objects self.sa_object = session.query(User).first() select = user_table.select() self.result_proxy = select.execute() self.row_proxy = select.execute().fetchone()
Example #13
Source File: test_provision.py From oslo.db with Apache License 2.0 | 5 votes |
def setUp(self): super(RetainSchemaTest, self).setUp() metadata = schema.MetaData() self.test_table = schema.Table( 'test_table', metadata, schema.Column('x', types.Integer), schema.Column('y', types.Integer), mysql_engine='InnoDB' ) def gen_schema(engine): metadata.create_all(engine, checkfirst=False) self._gen_schema = gen_schema
Example #14
Source File: test_provision.py From oslo.db with Apache License 2.0 | 5 votes |
def setUp(self): super(DropAllObjectsTest, self).setUp() self.metadata = metadata = schema.MetaData() schema.Table( 'a', metadata, schema.Column('id', types.Integer, primary_key=True), mysql_engine='InnoDB' ) schema.Table( 'b', metadata, schema.Column('id', types.Integer, primary_key=True), schema.Column('a_id', types.Integer, schema.ForeignKey('a.id')), mysql_engine='InnoDB' ) schema.Table( 'c', metadata, schema.Column('id', types.Integer, primary_key=True), schema.Column('b_id', types.Integer, schema.ForeignKey('b.id')), schema.Column( 'd_id', types.Integer, schema.ForeignKey('d.id', use_alter=True, name='c_d_fk')), mysql_engine='InnoDB' ) schema.Table( 'd', metadata, schema.Column('id', types.Integer, primary_key=True), schema.Column('c_id', types.Integer, schema.ForeignKey('c.id')), mysql_engine='InnoDB' ) metadata.create_all(self.engine, checkfirst=False) # will drop nothing if the test worked self.addCleanup(metadata.drop_all, self.engine, checkfirst=True)
Example #15
Source File: test_migrations.py From oslo.db with Apache License 2.0 | 5 votes |
def compare_type(self, ctxt, insp_col, meta_col, insp_type, meta_type): """Return True if types are different, False if not. Return None to allow the default implementation to compare these types. :param ctxt: alembic MigrationContext instance :param insp_col: reflected column :param meta_col: column from model :param insp_type: reflected column type :param meta_type: column type from model """ # some backends (e.g. mysql) don't provide native boolean type BOOLEAN_METADATA = (types.BOOLEAN, types.Boolean) BOOLEAN_SQL = BOOLEAN_METADATA + (types.INTEGER, types.Integer) if issubclass(type(meta_type), BOOLEAN_METADATA): return not issubclass(type(insp_type), BOOLEAN_SQL) # Alembic <=0.8.4 do not contain logic of comparing Variant type with # others. if isinstance(meta_type, types.Variant): orig_type = meta_col.type impl_type = meta_type.load_dialect_impl(ctxt.dialect) meta_col.type = impl_type try: return self.compare_type(ctxt, insp_col, meta_col, insp_type, impl_type) finally: meta_col.type = orig_type return ctxt.impl.compare_type(insp_col, meta_col)
Example #16
Source File: test_reflection.py From stdm with GNU General Public License v2.0 | 5 votes |
def test_nullable_reflection(self): t = Table('t', self.metadata, Column('a', Integer, nullable=True), Column('b', Integer, nullable=False)) t.create() eq_( dict( (col['name'], col['nullable']) for col in inspect(self.metadata.bind).get_columns('t') ), {"a": True, "b": False} )
Example #17
Source File: test_reflection.py From pyRevit with GNU General Public License v3.0 | 5 votes |
def define_tables(cls, metadata): Table( quoted_name('t1', quote=True), metadata, Column('id', Integer, primary_key=True), ) Table( quoted_name('t2', quote=True), metadata, Column('id', Integer, primary_key=True), Column('t1id', ForeignKey('t1.id')) )
Example #18
Source File: test_reflection.py From jbox with MIT License | 5 votes |
def define_tables(cls, metadata): Table('test_table', metadata, Column('id', Integer, primary_key=True), Column('data', String(50)) )
Example #19
Source File: annotation_database_parser.py From HistomicsTK with Apache License 2.0 | 5 votes |
def _add_item_to_sqlite(dbcon, item): # modify item info to prep for appending to sqlite table item_info = copy.deepcopy(item) item_info['largeImage'] = str(item_info['largeImage']) item_info_dtypes = { '_id': String(), '_modelType': String(), 'baseParentId': String(), 'baseParentType': String(), 'copyOfItem': String(), 'created': String(), 'creatorId': String(), 'description': String(), 'folderId': String(), 'largeImage': String(), 'name': String(), 'size': Integer(), 'updated': String(), } # in case anything is not in the schema, drop it item_info = { k: v for k, v in item_info.items() if k in item_info_dtypes.keys()} # convert to df and add to items table item_info_df = DataFrame.from_dict(item_info, orient='index').T item_info_df.to_sql( name='items', con=dbcon, if_exists='append', dtype=item_info_dtypes, index=False)
Example #20
Source File: db.py From huskar with MIT License | 5 votes |
def mysql_upsert(insert_stmt, compiler, **kwargs): # A modified version of https://gist.github.com/timtadh/7811458. # The license (3-Clause BSD) is in the repository root. parameters = insert_stmt.parameters if insert_stmt._has_multi_parameters: parameters = parameters[0] # pragma: no cover # TODO: fix keys = list(parameters or {}) pk = insert_stmt.table.primary_key auto = None if (len(pk.columns) == 1 and isinstance(pk.columns.values()[0].type, Integer) and pk.columns.values()[0].autoincrement): auto = pk.columns.keys()[0] if auto in keys: keys.remove(auto) insert = compiler.visit_insert(insert_stmt, **kwargs) ondup = 'ON DUPLICATE KEY UPDATE' updates = ', '.join( '%s = VALUES(%s)' % (c.name, c.name) for c in insert_stmt.table.columns if c.name in keys ) if auto is not None: last_id = '%s = LAST_INSERT_ID(%s)' % (auto, auto) if updates: updates = ', '.join((last_id, updates)) else: # pragma: no cover # TODO: fix updates = last_id upsert = ' '.join((insert, ondup, updates)) return upsert
Example #21
Source File: test_reflection.py From pyRevit with GNU General Public License v3.0 | 5 votes |
def define_tables(cls, metadata): Table('test_table', metadata, Column('id', Integer, primary_key=True), Column('data', String(50)) )
Example #22
Source File: __init__.py From parade with MIT License | 5 votes |
def sqltype_to_stdtype(sqltype): import sqlalchemy.types as sqltypes if isinstance(sqltype, (sqltypes.VARCHAR, sqltypes.CHAR, sqltypes.TEXT, sqltypes.Enum, sqltypes.String)): return _STRING_TYPE if isinstance(sqltype, (sqltypes.DATETIME, sqltypes.DATE, sqltypes.TIME, sqltypes.TIMESTAMP)): return _DATE_TYPE if isinstance(sqltype, (sqltypes.INTEGER, sqltypes.BIGINT, sqltypes.SMALLINT, sqltypes.Integer)): return _INTEGER_TYPE if isinstance(sqltype, (sqltypes.REAL, sqltypes.DECIMAL, sqltypes.NUMERIC, sqltypes.FLOAT)): return _DECIMAL_TYPE if isinstance(sqltype, sqltypes.BOOLEAN): return _BOOLEAN_TYPE
Example #23
Source File: test_reflection.py From planespotter with MIT License | 5 votes |
def define_tables(cls, metadata): Table( quoted_name('t1', quote=True), metadata, Column('id', Integer, primary_key=True), ) Table( quoted_name('t2', quote=True), metadata, Column('id', Integer, primary_key=True), Column('t1id', ForeignKey('t1.id')) )
Example #24
Source File: test_reflection.py From planespotter with MIT License | 5 votes |
def test_nullable_reflection(self): t = Table('t', self.metadata, Column('a', Integer, nullable=True), Column('b', Integer, nullable=False)) t.create() eq_( dict( (col['name'], col['nullable']) for col in inspect(self.metadata.bind).get_columns('t') ), {"a": True, "b": False} )
Example #25
Source File: test_reflection.py From planespotter with MIT License | 5 votes |
def define_tables(cls, metadata): Table('test_table', metadata, Column('id', Integer, primary_key=True), Column('data', String(50)) )
Example #26
Source File: type_api.py From planespotter with MIT License | 5 votes |
def _adapt_expression(self, op, other_comparator): """evaluate the return type of <self> <op> <othertype>, and apply any adaptations to the given operator. This method determines the type of a resulting binary expression given two source types and an operator. For example, two :class:`.Column` objects, both of the type :class:`.Integer`, will produce a :class:`.BinaryExpression` that also has the type :class:`.Integer` when compared via the addition (``+``) operator. However, using the addition operator with an :class:`.Integer` and a :class:`.Date` object will produce a :class:`.Date`, assuming "days delta" behavior by the database (in reality, most databases other than PostgreSQL don't accept this particular operation). The method returns a tuple of the form <operator>, <type>. The resulting operator and type will be those applied to the resulting :class:`.BinaryExpression` as the final operator and the right-hand side of the expression. Note that only a subset of operators make usage of :meth:`._adapt_expression`, including math operators and user-defined operators, but not boolean comparison or special SQL keywords like MATCH or BETWEEN. """ return op, self.type
Example #27
Source File: test_converter.py From graphene-sqlalchemy with MIT License | 5 votes |
def test_should_array_convert(): field = get_field(types.ARRAY(types.Integer)) assert isinstance(field.type, graphene.List) assert field.type.of_type == graphene.Int
Example #28
Source File: test_converter.py From graphene-sqlalchemy with MIT License | 5 votes |
def test_should_columproperty_convert(): field = get_field_from_column(column_property( select([func.sum(func.cast(id, types.Integer))]).where(id == 1) )) assert field.type == graphene.Int
Example #29
Source File: test_converter.py From graphene-sqlalchemy with MIT License | 5 votes |
def test_should_primary_integer_convert_id(): assert get_field(types.Integer(), primary_key=True).type == graphene.NonNull(graphene.ID)
Example #30
Source File: test_converter.py From graphene-sqlalchemy with MIT License | 5 votes |
def test_should_integer_convert_int(): assert get_field(types.Integer()).type == graphene.Int