Commit session error

Getting an error message while trying to run an apk through android studio 3.4 canary 1. Gradle plugin version com.android.tools.build:gradle:3.4.0-alpha01 Installation failed with message Faile...

Getting an error message while trying to run an apk through android studio 3.4 canary 1.

Gradle plugin version com.android.tools.build:gradle:3.4.0-alpha01

Installation failed with message Failed to commit install session 526049657 with command cmd package install-commit 526049657.. It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.

I have tried uninstalling the apk, restarting android studio and the device and invalidating caches and rebuilding but nothing seems to work.

Zoe stands with Ukraine's user avatar

asked Oct 23, 2018 at 6:47

Jude Fernandes's user avatar

Jude FernandesJude Fernandes

7,3179 gold badges51 silver badges90 bronze badges

2

I disabled «Instant Run» in settings, and it works for me.(Android Studio 3.4 canary)

picture

Then you can see the adb command executed in the terminal is «adb push», while it is «adb install-multiple» before that is disabled.

Milad Faridnia's user avatar

answered Dec 8, 2018 at 16:12

ime's user avatar

4

On Android studio go to build menu :
Build menu

Then:

  1. First Clean
  2. Rebuild
  3. run it again

*******It works well **********

Abdulrahman Falyoun's user avatar

answered May 25, 2019 at 15:47

Fitsum Alemu's user avatar

0

  1. build->clean project

  2. rebuild project

  3. Delete as shown below

enter image description here

answered Oct 23, 2018 at 7:24

initialise's user avatar

initialiseinitialise

2013 silver badges11 bronze badges

2

Disable «Instant Run».

File->Setting->Build, Execution, Deployment->Instant Run-> unCheck (Enable Instant Run to hot swap code/resource changes on deploy)

and Run your Project and after that go and Enable Instant Run to use the advantages of Instant Run

answered Jun 21, 2019 at 9:56

Mohammad Davari's user avatar

1

If you have a version of the APK installed on a device/emulator and you create a new version of the APK that compiles against an SDK above the device/emulator sdk, you get this error vs. the original «yo, you are targeting 28 and this device has 26… come one, you need a 28 device/emulator».

You have to actually turn off instant run to see the right error.

Why would you do this? Good question! I mixed up my Q vs P devices and wasted an hour trying to figure out what was going on. :P

answered Apr 28, 2019 at 21:36

codingjeremy's user avatar

codingjeremycodingjeremy

4,9271 gold badge34 silver badges38 bronze badges

Most easy solution is, wipe data of your emulator and run project again.

answered Jan 3, 2021 at 15:50

VIKAS SHARMA's user avatar

I had fixed this problem by getting rid of the meta data section in my manifest. I have no clue how it was added to the manifest to begin with (I’m a noob), but once I removed it from the manifest, the app loaded right up.

<Activity

/>

remove the meta data line within the manifest and it should work.

answered Dec 14, 2021 at 1:48

Jacqueline Woods's user avatar

1

This is what worked for me

Build > Clean Project

File > Invalidate Caches & Restart

answered May 28, 2022 at 10:38

abd3llatif's user avatar

abd3llatifabd3llatif

1501 silver badge6 bronze badges

Just checked In AndroidMainfest file is not complaining any issue.
I have updated targetSDK version 33 and it required «android:export» flag in activity section

answered Dec 12, 2022 at 9:41

Amit kumar's user avatar

@kirilgeorgiev82

Hello,

First, thank you very much for reviewing my request!

The issue is as follows: a flask app running on Ubuntu 18.04 (currently using the development server); in a view, a database record is retrieved, updated and then commited. However, the changes are not saved to the record and when it is next retrieved it still has its old values. For example:

@main_bp.route('/select-option', methods = ['GET', 'POST'])
def select_option():
...................
if request.method == 'POST':

       selected_value = request.form['whatever_key_is_relevant']

       record = Record.query.get(id)

       record.value_of_interest = selected.value

       try:
                db.session.add(record)

                db.session.commit() 
  
        except Exception as e:

                db.session.rollback()
                logging.exception(e)

So, the problem is that next time I retrieve the record, the changes are not persisted there.

Thank you very much in advance and your advice is very highly appreciated!

@miguelgrinberg

This isn’t really enough information for me to tell you what the problem is. The problem is likely not in this code, but instead in the configuration or set up of the application or the database.

@kirilgeorgiev82

Hi Miguel,

Thank you very much for your prompt answer! Indeed, probably this would be the case. I am using a PostgreSQL service from GCP. Another weird behaviour I see is that the following: the column I am trying to update is of db.PickeType where I want to keep a dictionary, which dictionary is supposed to help with maintaining user state. When I want to make updates in this dictionary like:

record = Record.query.get(id)
state = copy.copy(record.state)
state['new_thing'] = some_new_things
db.session.commit()

It works!

However, if I try to update this dictionary again, I get:

File "/home/kiril...../app/venv/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 628, i
n _collect_update_commands
   value, state.committed_state[propkey]
 File "/home/kiril....../app/venv_dev/lib/python3.6/site-packages/sqlalchemy/sql/sqltypes.py", line 1699, in 
compare_values
   return x == y
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()**

When I use the query.get() method I am not sure whether I receive the actual object or some copy (or proxy of it) which might be influencing the whole process. Would you have any idea what could be triggering this behaviour!

Very much appreciated!

Kind regards,
Kiril

@miguelgrinberg

I am not sure whether I receive the actual object

There is no concept of objects in the database. SQLAlchemy creates an object representation of the data stored in your database, so in a way all model instances are proxies that represent the real data.

What would be the purpose of doing these strange operations with copy on attributes of the model?

@kirilgeorgiev82

Hi Miguel,

Thank you for coming back to me. Let me try to create an example. Again, in a view:

@main_bp.route('/my-troubled-route'):
def my_troubled_route():
      state = UserState.query.get(the_unque_identifier)
    
      new_info = request.form['the_new_info_from_the_form']
      state.user_state_that_is_just_a_dictionary['new_info'] = new_info
      try:
              # db.session.add(state) - with or without this - it won't work
              db.session.commit()
      except Exception as e:
               logging.exception(e)

Result: 1) No errors whatsoever; 2) When I retrieve the respective user_state again, it is just not updated

So, if this is done:

@main_bp.route('/my-troubled-route'):
def my_troubled_route():
      state = UserState.query.get(the_unque_identifier)
      
       _temporary_state = copy.copy(state.user_state_that_is_just_a_dictionary)
      
      new_info = request.form['the_new_info_from_the_form']
      _temporary_state['new_info'] = new_info
      
      state.user_state_that_is_just_a_dictionary = _temporary_state

      try:
              db.session.commit()
      except Exception as e:
               logging.exception(e)

It does get saved in the db.

For me just making it work this way is far from enough and I would like to understand why I get this behaviour. An re the question why I tried with a copy, I had a similar problem with memory views in OpenCV (I know they are very, very different from what we have here, but I found an analogy with getting only access to proxies rather than the underlying data and decided to just try it out).

This is a frustrating one. Thank you very much once again, and for the book, and the tutorials….

@miguelgrinberg

What is the type of the dictionary attribute in your model?

@kirilgeorgiev82

It is state = db.Column(db.PickleType). My understanding is that it does pickle.dump and pickle.load automatically.

@miguelgrinberg

@kirilgeorgiev82

Thank you very much Miguel! Unfortunately, I had not come across this one (otherwise I did my fair share of reading before asking for your time, I presume how busy you are). I will have a very good look at this and will come back to you and maybe draft a better explanation so other users can benefit from it. Please let me know what you think?

Kind regards,
Kiril

@miguelgrinberg

@kirilgeorgiev82 yes, if you can post your working code here when you have it that would be awesome, as others will find it when they face the same problem. Thanks!

@kirilgeorgiev82

Thank you very much Miguel! Yes, please let me read the documentation you referenced, sort it out and I will post the solution here. Thank you and speak to you soon.

Best regards,
Kiril

@kirilgeorgiev82

Hi Miguel,

Please allow me to share the way I solved (or in my case it would be more accurate to say managed to avoid) the issue. As you pointed out to the specific part of SQLAlchemy documentation, in my understanding the problem was related to mutation tracking and establishing mutability of a python dictionary which is persisted in the database that way. Apart from the examples in the documentation above, there seems to be also a post by Frankster on StackOverflow with an example of implementing this.

In my case, I am creating an ephemeral user state which is created upon login and destroyed upon logout (I am familiar with Flask-Session but in my case I want something simpler and which I have full control over); further, it is fairly small and sufficiently fast to retrieve from the database; moreover, updates are fairly infrequent (e.g. once every few seconds or minutes, per user). So, I decided to avoid the relative complexity of the solution above and applied the following:

class State(db.Model):
     id = db.Column(db.String(32), index=True, primary_key=True)
     user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
     created_timestamp = db.Column(db.DateTime)
     modified_timestamp = db.Column(db.DateTime)
     closed_timestamp = db.Column(db.DateTime)
     state = db.Column(db.PickleType)  # This is where the dictionary is kept

     def some_method():
            ........
     def some_other_method():
           ........

def update_state(dictionary_with_state_updates, state_unique_id):
       current_state = State.query.get(state_unique_id)
       old_state_dictionary_which_will_be_updated = current_state.state
       old_state_dictionary_which_will_be_updated.update(dictionary_with_state_updates)
       
       refreshed_user_state = State(id=the_old_unique_id, 
                                                     created_timestamp=the_old_time_of_creation_timestamp,
                                                     modified_timestamp=datetime.datetime.utcnow(),
                                                     state =  old_state_dictionary_which_will_be_updated)
        db.session.delete(current_state)
        db.session.add(refreshed_user_state)
        try:
              db.session.commit()
       except Exception as e:
              db.session.rollback()
              logging.exception(e)

Whilst I acknowledge it is a ‘C-‘ solution in a broader sense, for my case is proved the best complexity / fitness-for-purpose trade off. Thanks once again!

Best regards,
Kiril

@richie312

you select this:

user = Users.query.filter_by(username='foo').first()

and save this

It is never gonna happen.

when you select, i think that’s using some flask-sqlalchemy syntactic sugar to select the session. a ‘raw’ sqlalchemy approach would typically be:

db.session.query(Users).filter_by(username='foo').first()

Source: https://groups.google.com/g/sqlalchemy/c/v8CURVXTkGA?pli=1

Answer by Jonanthan Vasco

Sessions / Queries¶

I’m re-loading data with my Session but it isn’t seeing changes that I committed elsewhere¶

The main issue regarding this behavior is that the session acts as though
the transaction is in the serializable isolation state, even if it’s not
(and it usually is not). In practical terms, this means that the session
does not alter any data that it’s already read within the scope of a transaction.

If the term “isolation level” is unfamiliar, then you first need to read this link:

Isolation Level

In short, serializable isolation level generally means
that once you SELECT a series of rows in a transaction, you will get
the identical data back each time you re-emit that SELECT. If you are in
the next-lower isolation level, “repeatable read”, you’ll
see newly added rows (and no longer see deleted rows), but for rows that
you’ve already loaded, you won’t see any change. Only if you are in a
lower isolation level, e.g. “read committed”, does it become possible to
see a row of data change its value.

For information on controlling the isolation level when using the
SQLAlchemy ORM, see Setting Transaction Isolation Levels / DBAPI AUTOCOMMIT.

To simplify things dramatically, the Session itself works in
terms of a completely isolated transaction, and doesn’t overwrite any mapped attributes
it’s already read unless you tell it to. The use case of trying to re-read
data you’ve already loaded in an ongoing transaction is an uncommon use
case that in many cases has no effect, so this is considered to be the
exception, not the norm; to work within this exception, several methods
are provided to allow specific data to be reloaded within the context
of an ongoing transaction.

To understand what we mean by “the transaction” when we talk about the
Session, your Session is intended to only work within
a transaction. An overview of this is at Managing Transactions.

Once we’ve figured out what our isolation level is, and we think that
our isolation level is set at a low enough level so that if we re-SELECT a row,
we should see new data in our Session, how do we see it?

Three ways, from most common to least:

  1. We simply end our transaction and start a new one on next access
    with our Session by calling Session.commit() (note
    that if the Session is in the lesser-used “autocommit”
    mode, there would be a call to Session.begin() as well). The
    vast majority of applications and use cases do not have any issues
    with not being able to “see” data in other transactions because
    they stick to this pattern, which is at the core of the best practice of
    short lived transactions.
    See When do I construct a Session, when do I commit it, and when do I close it? for some thoughts on this.

  2. We tell our Session to re-read rows that it has already read,
    either when we next query for them using Session.expire_all()
    or Session.expire(), or immediately on an object using
    refresh. See Refreshing / Expiring for detail on this.

  3. We can run whole queries while setting them to definitely overwrite
    already-loaded objects as they read rows by using “populate existing”.
    This is an execution option described at
    Populate Existing.

But remember, the ORM cannot see changes in rows if our isolation
level is repeatable read or higher, unless we start a new transaction
.

“This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar)¶

This is an error that occurs when a Session.flush() raises an exception, rolls back
the transaction, but further commands upon the Session are called without an
explicit call to Session.rollback() or Session.close().

It usually corresponds to an application that catches an exception
upon Session.flush() or Session.commit() and
does not properly handle the exception. For example:

from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base(create_engine("sqlite://"))


class Foo(Base):
    __tablename__ = "foo"
    id = Column(Integer, primary_key=True)


Base.metadata.create_all()

session = sessionmaker()()

# constraint violation
session.add_all([Foo(id=1), Foo(id=1)])

try:
    session.commit()
except:
    # ignore error
    pass

# continue using session without rolling back
session.commit()

The usage of the Session should fit within a structure similar to this:

try:
    # <use session>
    session.commit()
except:
    session.rollback()
    raise
finally:
    session.close()  # optional, depends on use case

Many things can cause a failure within the try/except besides flushes.
Applications should ensure some system of “framing” is applied to ORM-oriented
processes so that connection and transaction resources have a definitive
boundary, and so that transactions can be explicitly rolled back if any
failure conditions occur.

This does not mean there should be try/except blocks throughout an application,
which would not be a scalable architecture. Instead, a typical approach is
that when ORM-oriented methods and functions are first called, the process
that’s calling the functions from the very top would be within a block that
commits transactions at the successful completion of a series of operations,
as well as rolls transactions back if operations fail for any reason,
including failed flushes. There are also approaches using function decorators or
context managers to achieve similar results. The kind of approach taken
depends very much on the kind of application being written.

For a detailed discussion on how to organize usage of the Session,
please see When do I construct a Session, when do I commit it, and when do I close it?.

But why does flush() insist on issuing a ROLLBACK?¶

It would be great if Session.flush() could partially complete and then
not roll back, however this is beyond its current capabilities since its
internal bookkeeping would have to be modified such that it can be halted at
any time and be exactly consistent with what’s been flushed to the database.
While this is theoretically possible, the usefulness of the enhancement is
greatly decreased by the fact that many database operations require a ROLLBACK
in any case. Postgres in particular has operations which, once failed, the
transaction is not allowed to continue:

test=> create table foo(id integer primary key);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
CREATE TABLE
test=> begin;
BEGIN
test=> insert into foo values(1);
INSERT 0 1
test=> commit;
COMMIT
test=> begin;
BEGIN
test=> insert into foo values(1);
ERROR:  duplicate key value violates unique constraint "foo_pkey"
test=> insert into foo values(2);
ERROR:  current transaction is aborted, commands ignored until end of transaction block

What SQLAlchemy offers that solves both issues is support of SAVEPOINT, via
Session.begin_nested(). Using Session.begin_nested(), you can frame an operation that may
potentially fail within a transaction, and then “roll back” to the point
before its failure while maintaining the enclosing transaction.

But why isn’t the one automatic call to ROLLBACK enough? Why must I ROLLBACK again?¶

The rollback that’s caused by the flush() is not the end of the complete transaction
block; while it ends the database transaction in play, from the Session
point of view there is still a transaction that is now in an inactive state.

Given a block such as:

sess = Session()  # begins a logical transaction
try:
    sess.flush()

    sess.commit()
except:
    sess.rollback()

Above, when a Session is first created, assuming “autocommit mode”
isn’t used, a logical transaction is established within the Session.
This transaction is “logical” in that it does not actually use any database
resources until a SQL statement is invoked, at which point a connection-level
and DBAPI-level transaction is started. However, whether or not
database-level transactions are part of its state, the logical transaction will
stay in place until it is ended using Session.commit(),
Session.rollback(), or Session.close().

When the flush() above fails, the code is still within the transaction
framed by the try/commit/except/rollback block. If flush() were to fully
roll back the logical transaction, it would mean that when we then reach the
except: block the Session would be in a clean state, ready to
emit new SQL on an all new transaction, and the call to
Session.rollback() would be out of sequence. In particular, the
Session would have begun a new transaction by this point, which the
Session.rollback() would be acting upon erroneously. Rather than
allowing SQL operations to proceed on a new transaction in this place where
normal usage dictates a rollback is about to take place, the Session
instead refuses to continue until the explicit rollback actually occurs.

In other words, it is expected that the calling code will always call
Session.commit(), Session.rollback(), or Session.close()
to correspond to the current transaction block. flush() keeps the
Session within this transaction block so that the behavior of the
above code is predictable and consistent.

How do I make a Query that always adds a certain filter to every query?¶

See the recipe at FilteredQuery.

My Query does not return the same number of objects as query.count() tells me — why?¶

The Query object, when asked to return a list of ORM-mapped objects,
will deduplicate the objects based on primary key. That is, if we
for example use the User mapping described at Using ORM Declarative Forms to Define Table Metadata,
and we had a SQL query like the following:

q = session.query(User).outerjoin(User.addresses).filter(User.name == "jack")

Above, the sample data used in the tutorial has two rows in the addresses
table for the users row with the name 'jack', primary key value 5.
If we ask the above query for a Query.count(), we will get the answer
2:

However, if we run Query.all() or iterate over the query, we get back
one element:

>>> q.all()
[User(id=5, name='jack', ...)]

This is because when the Query object returns full entities, they
are deduplicated. This does not occur if we instead request individual
columns back:

>>> session.query(User.id, User.name).outerjoin(User.addresses).filter(
...     User.name == "jack"
... ).all()
[(5, 'jack'), (5, 'jack')]

There are two main reasons the Query will deduplicate:

  • To allow joined eager loading to work correctlyJoined Eager Loading
    works by querying rows using joins against related tables, where it then routes
    rows from those joins into collections upon the lead objects. In order to do this,
    it has to fetch rows where the lead object primary key is repeated for each
    sub-entry. This pattern can then continue into further sub-collections such
    that a multiple of rows may be processed for a single lead object, such as
    User(id=5). The dedpulication allows us to receive objects in the way they
    were queried, e.g. all the User() objects whose name is 'jack' which
    for us is one object, with
    the User.addresses collection eagerly loaded as was indicated either
    by lazy='joined' on the relationship() or via the joinedload()
    option. For consistency, the deduplication is still applied whether or not
    the joinedload is established, as the key philosophy behind eager loading
    is that these options never affect the result.

  • To eliminate confusion regarding the identity map — this is admittedly
    the less critical reason. As the Session
    makes use of an identity map, even though our SQL result set has two
    rows with primary key 5, there is only one User(id=5) object inside the Session
    which must be maintained uniquely on its identity, that is, its primary key /
    class combination. It doesn’t actually make much sense, if one is querying for
    User() objects, to get the same object multiple times in the list. An
    ordered set would potentially be a better representation of what Query
    seeks to return when it returns full objects.

The issue of Query deduplication remains problematic, mostly for the
single reason that the Query.count() method is inconsistent, and the
current status is that joined eager loading has in recent releases been
superseded first by the “subquery eager loading” strategy and more recently the
“select IN eager loading” strategy, both of which are generally more
appropriate for collection eager loading. As this evolution continues,
SQLAlchemy may alter this behavior on Query, which may also involve
new APIs in order to more directly control this behavior, and may also alter
the behavior of joined eager loading in order to create a more consistent usage
pattern.

I’ve created a mapping against an Outer Join, and while the query returns rows, no objects are returned. Why not?¶

Rows returned by an outer join may contain NULL for part of the primary key,
as the primary key is the composite of both tables. The Query object ignores incoming rows
that don’t have an acceptable primary key. Based on the setting of the allow_partial_pks
flag on Mapper, a primary key is accepted if the value has at least one non-NULL
value, or alternatively if the value has no NULL values. See allow_partial_pks
at Mapper.

I’m using joinedload() or lazy=False to create a JOIN/OUTER JOIN and SQLAlchemy is not constructing the correct query when I try to add a WHERE, ORDER BY, LIMIT, etc. (which relies upon the (OUTER) JOIN)¶

The joins generated by joined eager loading are only used to fully load related
collections, and are designed to have no impact on the primary results of the query.
Since they are anonymously aliased, they cannot be referenced directly.

For detail on this behavior, see The Zen of Joined Eager Loading.

Query has no __len__(), why not?¶

The Python __len__() magic method applied to an object allows the len()
builtin to be used to determine the length of the collection. It’s intuitive
that a SQL query object would link __len__() to the Query.count()
method, which emits a SELECT COUNT. The reason this is not possible is
because evaluating the query as a list would incur two SQL calls instead of
one:

class Iterates:
    def __len__(self):
        print("LEN!")
        return 5

    def __iter__(self):
        print("ITER!")
        return iter([1, 2, 3, 4, 5])


list(Iterates())

output:

How Do I use Textual SQL with ORM Queries?¶

See:

  • Getting ORM Results from Textual Statements — Ad-hoc textual blocks with Query

  • Using SQL Expressions with Sessions — Using Session with textual SQL directly.

I’m calling Session.delete(myobject) and it isn’t removed from the parent collection!¶

See Notes on Delete — Deleting Objects Referenced from Collections and Scalar Relationships for a description of this behavior.

why isn’t my __init__() called when I load objects?¶

See Constructors and Object Initialization for a description of this behavior.

how do I use ON DELETE CASCADE with SA’s ORM?¶

SQLAlchemy will always issue UPDATE or DELETE statements for dependent
rows which are currently loaded in the Session. For rows which
are not loaded, it will by default issue SELECT statements to load
those rows and update/delete those as well; in other words it assumes
there is no ON DELETE CASCADE configured.
To configure SQLAlchemy to cooperate with ON DELETE CASCADE, see
Using foreign key ON DELETE cascade with ORM relationships.

I set the “foo_id” attribute on my instance to “7”, but the “foo” attribute is still None — shouldn’t it have loaded Foo with id #7?¶

The ORM is not constructed in such a way as to support
immediate population of relationships driven from foreign
key attribute changes — instead, it is designed to work the
other way around — foreign key attributes are handled by the
ORM behind the scenes, the end user sets up object
relationships naturally. Therefore, the recommended way to
set o.foo is to do just that — set it!:

foo = session.get(Foo, 7)
o.foo = foo
Session.commit()

Manipulation of foreign key attributes is of course entirely legal. However,
setting a foreign-key attribute to a new value currently does not trigger
an “expire” event of the relationship() in which it’s involved. This means
that for the following sequence:

o = session.scalars(select(SomeClass).limit(1)).first()

# assume the existing o.foo_id value is None;
# accessing o.foo will reconcile this as ``None``, but will effectively
# "load" the value of None
assert o.foo is None

# now set foo_id to something.  o.foo will not be immediately affected
o.foo_id = 7

o.foo is loaded with its effective database value of None when it
is first accessed. Setting
o.foo_id = 7 will have the value of “7” as a pending change, but no flush
has occurred — so o.foo is still None:

# attribute is already "loaded" as None, has not been
# reconciled with o.foo_id = 7 yet
assert o.foo is None

For o.foo to load based on the foreign key mutation is usually achieved
naturally after the commit, which both flushes the new foreign key value
and expires all state:

session.commit()  # expires all attributes

foo_7 = session.get(Foo, 7)

# o.foo will lazyload again, this time getting the new object
assert o.foo is foo_7

A more minimal operation is to expire the attribute individually — this can
be performed for any persistent object using Session.expire():

o = session.scalars(select(SomeClass).limit(1)).first()
o.foo_id = 7
Session.expire(o, ["foo"])  # object must be persistent for this

foo_7 = session.get(Foo, 7)

assert o.foo is foo_7  # o.foo lazyloads on access

Note that if the object is not persistent but present in the Session,
it’s known as pending. This means the row for the object has not been
INSERTed into the database yet. For such an object, setting foo_id does not
have meaning until the row is inserted; otherwise there is no row yet:

new_obj = SomeClass()
new_obj.foo_id = 7

Session.add(new_obj)

# returns None but this is not a "lazyload", as the object is not
# persistent in the DB yet, and the None value is not part of the
# object's state
assert new_obj.foo is None

Session.flush()  # emits INSERT

assert new_obj.foo is foo_7  # now it loads

The recipe ExpireRelationshipOnFKChange features an example using SQLAlchemy events
in order to coordinate the setting of foreign key attributes with many-to-one
relationships.

Is there a way to automagically have only unique keywords (or other kinds of objects) without doing a query for the keyword and getting a reference to the row containing that keyword?¶

When people read the many-to-many example in the docs, they get hit with the
fact that if you create the same Keyword twice, it gets put in the DB twice.
Which is somewhat inconvenient.

This UniqueObject recipe was created to address this issue.

Why does post_update emit UPDATE in addition to the first UPDATE?¶

The post_update feature, documented at Rows that point to themselves / Mutually Dependent Rows, involves that an
UPDATE statement is emitted in response to changes to a particular
relationship-bound foreign key, in addition to the INSERT/UPDATE/DELETE that
would normally be emitted for the target row. While the primary purpose of this
UPDATE statement is that it pairs up with an INSERT or DELETE of that row, so
that it can post-set or pre-unset a foreign key reference in order to break a
cycle with a mutually dependent foreign key, it currently is also bundled as a
second UPDATE that emits when the target row itself is subject to an UPDATE.
In this case, the UPDATE emitted by post_update is usually unnecessary
and will often appear wasteful.

However, some research into trying to remove this “UPDATE / UPDATE” behavior
reveals that major changes to the unit of work process would need to occur not
just throughout the post_update implementation, but also in areas that aren’t
related to post_update for this to work, in that the order of operations would
need to be reversed on the non-post_update side in some cases, which in turn
can impact other cases, such as correctly handling an UPDATE of a referenced
primary key value (see #1063 for a proof of concept).

The answer is that “post_update” is used to break a cycle between two
mutually dependent foreign keys, and to have this cycle breaking be limited
to just INSERT/DELETE of the target table implies that the ordering of UPDATE
statements elsewhere would need to be liberalized, leading to breakage
in other edge cases.

SQLAlchemy, как и многие другие ОРМ работает с базой данных через сессии. Это отличается от работы на прямую с базой данных. Не понимания принципа работы сессий может приводить к надоедливым ошибкам.

Ошибки

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3)

«attribute refresh operation cannot proceed» % (state_str(state))
sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3)

Как избежать ошибок на примере кода ниже, где все работает корректно:

def ploshadka_function(self):

    # Положим в переменную все ID пользователей (чтобы потом работать с другой сессией)
    user_ids = [x.id for x in db.session.query(User.id).distinct()]

    for x_id in user_ids:
        # Теперь мы можем работать с новой сессией
        user = db.session.query(User).filter_by(id=x_id).first()

        for setting in user.settings:
            row = vars(setting)

            if row[‘name’] == ‘market_direction’:
                self.send_market_direction(user)

            elif row[‘name’] == ‘change_percent’:
                self.send_change_percent(user, row[‘percent’])

            # Обновляем дату
            db.session.query(UserSetting).filter_by(name=row[‘name’]).update({‘key’: value})

        # Коммитим все изменения после обработки одного пользователя
        db.session.commit()

В этом коде могло быть 2 ошибки в пересечениях сессий.

1.
Если бы мы использовали db.session.commit() внутри второго цикла for, то SQLAlchemy закрыл бы сессию, посчитав, что задача выполнена.

Вместо этого мы обновляем методом update наш экземпляр класса User, созданный выше. А в самом конце делаем commit.

2.
Но db.session.commit() все еще внутри первого цикла и мы не можем вынести его за него. Поэтому мы кладем наверху ID пользователей в переменную user_ids. ID собраны отдельно и при закрытии сессии нам не страшно, что закроется сеанс.

Например, такой код при взаимодействии выше, вызвал бы ошибки с сессиями:

users = db.session.query(User).all()
for user in users:
   settings = db.session.query(UserSetting).filter_by(user_id=user.id).all()

Это произошло бы из-за db.session.commit() внутри первого цикла for. После первого прохода в переменной users ничего бы не осталось. И во втором проходе возникла бы ошибка «Instance is not bound to a Session».

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from flask import Flask, render_template, url_for, request, redirect, flash, session
from flask_sqlalchemy import SQLAlchemy
import datetime
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import check_password_hash, generate_password_hash
 
 
app = Flask(__name__)
app.secret_key = 'zondercraftwarzeig'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
manager = LoginManager(app)
 
 
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(30), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
 
    def __repr__(self):
        return f'<{self.login}:{self.id}>'
 
 
class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    author = db.Column(db.String(30))
 
    def __repr__(self):
        return f'<Article {self.id}>'
 
 
@manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
 
 
@app.route('/')
@app.route('/home')
def index():
    return render_template('articles.html')
 
 
@app.route('/login', methods=['GET', 'POST'])
def login_page():
    login = request.form.get('login')
    password = request.form.get('password')
    if request.method == 'POST':
        if login and password:
            user = User.query.filter_by(login=login).first()
            if user and check_password_hash(user.password, password):
                login_user(user)
                next_page = request.args.get('next')
                return redirect(url_for('user_page'))
            else:
                flash('Неверное имя пользователя или пароль')
        else:
            flash('Пожалуйста, заполните все поля')
    return render_template('login.html')
 
 
@app.route('/register', methods=['GET', 'POST'])
def register():
    login = request.form.get('login')
    password = request.form.get('password')
    password2 = request.form.get('password2')
    if request.method == 'POST':
        if not (login or password or password2):
            flash('Пожалуйста, заполните все поля')
        elif password != password2:
            flash('Пароли разные')
        else:
            hash_password = generate_password_hash(password)
            print('hash is ready')
            new_user = User(login=login, password=hash_password)
            print('new_user created')
            db.session.add(new_user)
            db.session.commit()
            print('User created successfully')
            return redirect(url_for('login_page'))
 
    return render_template('register.html')
 
 
@app.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
    logout_user()
    print('user вышел')
    return redirect('/')
 
 
@app.after_request
def redirect_to_signin(response):
    if response.status_code == 401:
        return redirect(url_for('login_page') + '?next=' + request.url)
    return response
 
 
@app.route('/about')
def contacts():
    return render_template('contacts.html')
 
 
@app.route('/articles')
def articles():
    arts = Article.query.order_by(Article.date.desc()).all()
    return render_template('articles.html', arts=arts)
 
 
@app.route('/articles/<int:id>')
def article_detail(id):
    art = Article.query.get(id)
    return render_template('article_detail.html', art=art)
 
 
@app.route('/articles/<int:id>/delete')
@login_required
def article_delete(id):
    art = Article.query.get_or_404(id)
    try:
        db.session.delete(art)
        db.session.commit()
        return redirect('/articles')
    except:
        return 'При удалении статьи произошла ошибка'
 
 
@app.route('/user_page', methods=['POST', 'GET'])
@login_required
def user_page():
    user = current_user.login
    my_articles = Article.query.filter(Article.author == user).all()
    return render_template('user_page.html', my_articles=my_articles)
 
 
@app.route('/create_article', methods=['POST', 'GET'])
@login_required
def create_article():
    if request.method == 'POST':
        title = request.form['title']
        intro = request.form['intro']
        text = request.form['text']
        date = datetime.datetime.utcnow
        article = Article(title=title, intro=intro, text=text, date=date, author=current_user.login)
        try:
            db.session.add(article)
            print('Article added')
            db.session.commit()
            print('Article commited')
            return redirect('/articles')
        except:
            return "При добавлении произошла ошибка"
    else:
        return render_template('create_article.html')

SQLAlchemy, like many other ORMs, works with the database through sessions. This is different from working directly with the database. Not understanding how sessions work can lead to annoying errors.

Errors

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3)

“Attribute refresh operation cannot proceed”% (state_str (state))
sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/13/bhk3)

How to avoid errors using the example code below, where everything works correctly:

def ploshadka_function(self):

# Put all user IDs in a variable (to work with another session later)
user_ids = [x.id for x in db.session.query(User.id).distinct()]

for x_id in user_ids:
# Now we can work with a new session
user = db.sessionquery(User)filter_by(id=x_id)first()

for setting in usersettings:
row = vars(setting)

if row[‘name’] == ‘market_direction’:
selfsend_market_direction(user)

elif row[‘name’] == ‘change_percent’:
selfsend_change_percent(user, row[‘percent’])

# Update the date
db.sessionquery(UserSetting)filter_by(name=row[‘name’])update({‘key’: value})

# Commit all changes after processing one user
db.sessioncommit()

This code could have 2 errors in the intersection of sessions.

1.
If we used db.session.commit () inside second cycle forthen SQLAlchemy would close the session assuming the task is complete.

Instead, we update with the method update our class instance Usercreated above. And at the very end we do commit

2.
But db.session.commit () is still inside the first cycle and we cannot bear it outside of it. Therefore, we put the user IDs at the top in a variable user_ids… IDs are collected separately and when the session is closed, we are not afraid that the session will close.

For example, this code, when interacting above, would cause errors with sessions:

users = db.sessionquery(User)all()
for user in users:
settings = db.sessionquery(UserSetting)filter_by(user_id=userid)all()

This would be due to db.session.commit () inside the first loop for… After the first pass in the variable users nothing would be left. And in the second pass there would be an error Instance is not bound to a Session “

943

Получение сообщения об ошибке при попытке запустить apk через android studio 3.4 canary 1.

Версия плагина Gradle com.android.tools.build:gradle:3.4.0-alpha01

Installation failed with message Failed to commit install session 526049657 with command cmd package install-commit 526049657.. It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.

Я попытался удалить apk, перезапустить студию Android и устройство, аннулировать кеши и перестроить, но, похоже, ничего не работает.


Ответы
6

  1. Build-> чистый проект

  2. Перестроить проект

  3. Удалить, как показано ниже

Я отключил «Мгновенный запуск» в настройках, и он у меня работает. (Android Studio 3.4 canary)

Затем вы можете увидеть, что команда adb, выполняемая в терминале, — это «adb push», а перед отключением — «adb install-multiple».

Если у вас есть версия APK, установленная на устройстве / эмуляторе, и вы создаете новую версию APK, которая компилируется с SDK выше SDK устройства / эмулятора, вы получаете эту ошибку по сравнению с исходным «yo, вы нацелены на 28 а у этого устройства 26 … иди один, тебе нужен 28 девайс / эмулятор «.

Вы должны фактически отключить мгновенный запуск, чтобы увидеть правильную ошибку.

Зачем тебе это делать? Хороший вопрос! Я перепутал свои устройства Q и P и потратил час, пытаясь понять, что происходит. :П

В Android Studio перейдите в меню сборки:
Меню сборки

Потом:

First Clean
Rebuild
run it again

*******Это работает хорошо **********

Отключите «Мгновенный запуск».

File-> Setting-> Build, Execution, Deployment-> Instant Run-> unCheck (Включить мгновенный запуск для изменения кода / ресурсов горячей замены при развертывании)

И запустите свой проект, а затем перейдите и включите мгновенный запуск, чтобы использовать преимущества мгновенного запуска

Самое простое решение — стереть данные вашего эмулятора и снова запустить проект.

Другие вопросы по теме

Понравилась статья? Поделить с друзьями:
  • Commit has 2 parents как исправить
  • Commit failed with error 0 files committed
  • Commit data error xmlhttp undefined что это
  • Comment failed to post как исправить
  • Comment acceptsecuritycontext error data 52e v1db1