def get_user_id(cls, field_name, field_value): db_conf, tb_shard = models.get_db_table(field_value) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) sql = 'SELECT `user_id` FROM `%s` WHERE `field_name`=%%s AND `field_value`=%%s' % (tb_name,) row = cnn.get(sql, field_name, field_value) return row.user_id finally: cnn.close()
def get(cls, id): db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) sql = 'SELECT * FROM `%s` WHERE `%s`=%%s' % (tb_name, cls.__pk__,) row = cnn.get(sql, id) return cls(**row) finally: cnn.close()
def __init__(self): Connection.__init__(self) self.url = '' self.type_name = '' self.symbols = [] self.pattern = Template('(?<!\w)(' '${fullNameLower}|' '${fullNameTitle}|' '${symbolLower}|' '${symbolUpper}|' ')(?!\w)')
def get_friends(cls, user_id): """返回好友列表""" db_conf, tb_shard = models.get_db_table(user_id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) sql = 'SELECT `id`, `user_id`, `friend_id`, `created_at` FROM `%s` WHERE `user_id`=%%s' % (tb_name,) iter = cnn.iter(sql, user_id) return [cls(**row) for row in iter] finally: cnn.close()
def delete(self): """删除当前对象""" cls = self.__class__ id = getattr(self, cls.__pk__) db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) sql = 'DELETE FROM `%s` WHERE `%s`=%%s' % (tb_name, cls.__pk__,) return cnn.execute(sql, id) finally: cnn.close()
def set_syntax_tree(self): Connection.set(self, query_params={ 'tablename': 'entity_syntax', 'fields': { 'entity_id': self.id, 'pos': pos, 'word': word, 'distance_measure_string': distance_measure_string } })
def get_user_id(cls, field_name, field_value): db_conf, tb_shard = models.get_db_table(field_value) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % ( cls.__tablename__, tb_shard, ) sql = 'SELECT `user_id` FROM `%s` WHERE `field_name`=%%s AND `field_value`=%%s' % ( tb_name, ) row = cnn.get(sql, field_name, field_value) return row.user_id finally: cnn.close()
def connection(): connection = Connection(password='******', db_name='test') connection.drop_db() connection.connect() yield connection connection.drop_db()
def get(cls, id): db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % ( cls.__tablename__, tb_shard, ) sql = 'SELECT * FROM `%s` WHERE `%s`=%%s' % ( tb_name, cls.__pk__, ) row = cnn.get(sql, id) return cls(**row) finally: cnn.close()
def __init__(self, name, number, vendor, payment_id, balance=None): self.name = name self.number = number self.vendor = vendor self.connection = Connection() self.balance = balance self.payment_id = payment_id
def __init__(self, title, date, description, url, metadata={}): Connection.__init__(self) url_parts = urlparse(url) self.id = 0 self.title = title self.date = date self.url = url self.source = url_parts.netloc self.metadata = metadata self.description = description # self.scrape_meta_tags(['description']) self.syntax_tree = {} # self.construct_syntax_tree() self.set()
def delete(self): """删除当前对象""" cls = self.__class__ id = getattr(self, cls.__pk__) db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % ( cls.__tablename__, tb_shard, ) sql = 'DELETE FROM `%s` WHERE `%s`=%%s' % ( tb_name, cls.__pk__, ) return cnn.execute(sql, id) finally: cnn.close()
def update(self): """修改当前对象""" cls = self.__class__ id = getattr(self, cls.__pk__) db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) attrs = self.__dict__ sql = 'UPDATE `%s` SET %s WHERE `%s`=%%s' % ( tb_name, ', '.join(['%s=%%s' % x for x in attrs if x != cls.__pk__]), cls.__pk__, ) parameters = [attrs[x] for x in attrs if x != cls.__pk__] parameters.append(getattr(self, cls.__pk__)) return cnn.execute(sql, *parameters) finally: cnn.close()
def insert(self): """插入当前对象""" cls = self.__class__ if cls.__shard_field__: db_conf, tb_shard = get_db_table(getattr(self, cls.__shard_field__)) else: print cls.__insert_counter__ db_conf, tb_shard = get_db_table(cls.__insert_counter__) cls.__insert_counter__ = cls.__insert_counter__ + 1 if cls.__insert_counter__ >= settings.DB_TABLES_LEN: cls.__insert_counter__ = 0 cnn = Connection(*db_conf) print 'db = %s ' % db_conf[1] try: tb_name = '%s_%d' % (cls.__tablename__, tb_shard,) sql = "UPDATE `seq` SET `id`=LAST_INSERT_ID(`id`+%d) WHERE `tb`=%%s" % settings.DB_TABLES_LEN print sql % tb_name id = cnn.execute(sql, tb_name) print 'lastid %d' % id setattr(self, cls.__pk__, id) attrs = self.__dict__ sql = "INSERT INTO `%s` (%s) VALUES (%s)" % ( tb_name, ', '.join(map(lambda x: '`%s`' % x, attrs)), ', '.join(['%s' for _ in attrs]), ) print sql parameters = [attrs[x] for x in attrs] cnn.execute(sql, *parameters) return getattr(self, cls.__pk__) finally: cnn.close()
def update(self): """修改当前对象""" cls = self.__class__ id = getattr(self, cls.__pk__) db_conf, tb_shard = get_db_table(id) cnn = Connection(*db_conf) try: tb_name = '%s_%d' % ( cls.__tablename__, tb_shard, ) attrs = self.__dict__ sql = 'UPDATE `%s` SET %s WHERE `%s`=%%s' % ( tb_name, ', '.join(['%s=%%s' % x for x in attrs if x != cls.__pk__]), cls.__pk__, ) parameters = [attrs[x] for x in attrs if x != cls.__pk__] parameters.append(getattr(self, cls.__pk__)) return cnn.execute(sql, *parameters) finally: cnn.close()
def set_relationship(self, entity, search_text): for coin in self.symbols: # Compile regex regex = re.compile( self.pattern.substitute( fullNameLower=coin.full_name.lower(), fullNameTitle=coin.full_name.title(), symbolLower=coin.symbol.lower(), symbolUpper=coin.symbol.upper() ), re.S ) # Search provided text for symbols result = regex.search(search_text) if (result): # set relationship between entity_id and symbol_id, if found Connection.set(self, query_params={ 'tablename': 'entity_symbol_lookup', 'fields': { 'entity_id': entity.id, 'symbol_id': coin.symbol_id, } })
def main(): conn = Connection() try: with start_transaction(conn) as tx: x = 1 + 1 raise ValueError y = x + 2 print("transaction 0 =", x, y) except ValueError: print("OOPS Transaction failed") try: with start_transaction(conn) as tx: x = 1 + 1 y = x + 2 print("transaction 0 =", x, y) except ValueError: print("OOPS Transaction failed")
def set(self): entity_id = Connection.set( self, query_params={ 'tablename': 'entity', 'returning': ['entity_id'], 'fields': { 'title': self.title, 'url': self.url, 'publish_date': self.date, 'description': self.description, 'meta_data': json.dumps(self.metadata), 'syntax_tree': json.dumps(self.syntax_tree), 'entity_type_id': 0, # @todo make this a real entity type ID } }) print entity_id[0] self.id = entity_id[0]
def get(self, feed_type_id): fields = ['feed_id', 'url', 'feed_type_id', 'symbol_type_id'] # get all available feeds of provided type feeds = Connection.get(self, query_params={ 'tablename': 'feed', 'fields': fields, 'where_stmt': [{ 'key': 'feed_type_id', 'value': feed_type_id }] }) # loop feeds, create a new feed class, # and associate with a symbol type class for use in entity processing for feed in feeds: values = dict(zip(fields, list(feed))) new_feed = Feed(**values) new_feed.symbol_type_class = self.symbol_type_class_mapping[ new_feed.symbol_type_id] self.feeds.append(new_feed)
def insert(self): """插入当前对象""" cls = self.__class__ if cls.__shard_field__: db_conf, tb_shard = get_db_table(getattr(self, cls.__shard_field__)) else: print cls.__insert_counter__ db_conf, tb_shard = get_db_table(cls.__insert_counter__) cls.__insert_counter__ = cls.__insert_counter__ + 1 if cls.__insert_counter__ >= settings.DB_TABLES_LEN: cls.__insert_counter__ = 0 cnn = Connection(*db_conf) print 'db = %s ' % db_conf[1] try: tb_name = '%s_%d' % ( cls.__tablename__, tb_shard, ) sql = "UPDATE `seq` SET `id`=LAST_INSERT_ID(`id`+%d) WHERE `tb`=%%s" % settings.DB_TABLES_LEN print sql % tb_name id = cnn.execute(sql, tb_name) print 'lastid %d' % id setattr(self, cls.__pk__, id) attrs = self.__dict__ sql = "INSERT INTO `%s` (%s) VALUES (%s)" % ( tb_name, ', '.join(map(lambda x: '`%s`' % x, attrs)), ', '.join(['%s' for _ in attrs]), ) print sql parameters = [attrs[x] for x in attrs] cnn.execute(sql, *parameters) return getattr(self, cls.__pk__) finally: cnn.close()
def get(self, symbol_type_id): fields = [ 'symbol_id', 'symbol_type_id', 'symbol', 'name', 'full_name', 'meta', ] symbols = Connection.get(self, query_params={ 'tablename': 'symbol', 'fields': fields, 'where_stmt': [{ 'key': 'symbol_type_id', 'value': symbol_type_id }] }) for symbol in symbols: values = dict(zip(fields, list(symbol))) self.symbols.append(Symbol(**values))
def __init__(self): Connection.__init__(self) exchanges = self.get_exchanges() for exchange in exchanges: source = self.request_source(exchange[2]) symbol_exchange_rates = json.loads(source) for sym in symbol_exchange_rates: # TODO: Load correct endpoint field names by exchange args = { 'tablename': 'symbol', 'conditional': 'AND', 'where_stmt': [{ 'key': 'symbol', 'value': sym['symbol'], 'operator': '=' }, { 'key': 'symbol_type_id', 'value': exchange[1], 'operator': '=' }] } exists = Connection.exists(self, args) # Add symbol to table if it does not exist. if (not exists): Connection.set(self, query_params={ 'tablename': 'symbol', 'fields': { 'symbol_type_id': exchange[1], 'symbol': sym['symbol'], 'name': sym['id'], 'meta': '', 'full_name': sym['name'] } }) # Get our symbol id # TODO: We need to grab this symbol id from an object cache. # See https://trello.com/c/nivVoxpF symbol_id = Connection.get(self, query_params={ 'tablename': 'symbol', 'where_stmt': [{ 'key': 'symbol', 'value': sym['symbol'], 'operator': '=' }, { 'key': 'symbol_type_id', 'value': exchange[1], 'operator': '=' }], 'fields': ['symbol_id'] }) # Insert most recent exchange rate. if (sym['last_updated']): Connection.set( self, query_params={ 'tablename': 'symbol_exchange_rate_lookup', 'fields': { 'exchange_id': exchange[0], 'symbol_id': symbol_id[0][0], 'rate': sym['price_usd'], 'date': Connection.convert_timestamp_to_datetime( self, sym['last_updated']) } })
def __init__(self): SymbolType.__init__(self) Connection.__init__(self) self.get(self.symbol_type_id)
def __init__(self): self.config = Config() self.path = self.config.get_base_dir('var') + 'log/' self.time = Time() self.email_transport = EmailTransport() self.connection = Connection()
def init_database(): connect = Connection() is_db_empty = connect.create_connection(alias) if is_db_empty: insert_all_models_data()
def __init__(self): self.connection = Connection()
def __init__(self, connection: Connection): self.connection = connection.connect() print('Connected to database Successfully') self.cursor = self.connection.cursor()
def __init__(self): self.graph = Connection.get_instance().get_connection()
def __init__(self, status=1): self.status = status self.connection = Connection()
def __init__(self): self.graph = Connection.get_instance().get_connection() self.nodes = NodeMatcher(self.graph) PlacesController.__instance = self
def main(): Migration(Connection(cwd)).run_migrations()
#!/usr/local/bin/python3 import string, os from db.connection import Connection from db.schema import account_schema from utils.consprint import ConsolePrinter from utils.router import Router Connection(':memory:').createTable(**account_schema) kwargs_keys = [ "name", "age", "password", "coins", "user_type", "coin_limit", "initial_bet", "reward" ] # define the router decorator class Session: __consoleMainOptions = ['PLAY', 'QUIT'] def __init__(self): self.currMod = 'intro' @Router.default('home') def Introduction(self): modTitle = "MINI-CASINO" modDesc = "Welcome to the {}! This is an experimental game, accessed through the terminal. The game can only played with an account, so please sign up or login using account.".format( moduleTitle.title()) modKeyMap = {} return input('Press Letter: ') @Router.special('register') def Registration(self):
def __init__(self): Connection.__init__(self) self.feeds = []